python 实现 ssh 远程登陆
通过 os 模块实现import os result = os.system('ssh localhost -p7021')#现场机做过远程登陆
''' def system() #Execute the command in a subshell pass ''' os.system 方法本质上是调用c标准库中的的system()实现的 返回一个执行结果,执行成功,结果是0
result2 = os.popen('ssh localhost -p7021') '''
def popen(): if not isinstance(cmd, str): raise TypeError("invalid cmd type (%s, expected string)" % type(cmd)) if mode not in ("r", "w"): raise ValueError("invalid mode %r" % mode) if buffering == 0 or buffering is None: raise ValueError("popen() does not support unbuffered streams") import subprocess, io if mode == "r": proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, bufsize=buffering) return _wrap_close(io.TextIOWrapper(proc.stdout), proc) else: proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, bufsize=buffering) return _wrap_close(io.TextIOWrapper(proc.stdin), proc) ''' 返回一个文件输入输出对象,可以popen()中 设置mode 参数为'w'或者'r' 本质上调用的是 subprocess中的Popen 中的方法
通过 subprocess 实现登录
import subprocess pass
通过 paramiko 实现
#!/usr/bin/python # -*- coding: UTF-8 -*- import paramiko # 实例化SSHClient client = paramiko.SSHClient() # 自动添加策略,保存服务器的主机名和密钥信息,如果不添加,那么不在本地know_hosts文件中记录的主机将无法连接 client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 连接SSH服务端,以用户名和密码进行认证 client.connect(hostname='localhost', port=8045, username='pi', password='123456') # 打开一个Channel并执行命令 stdin, stdout, stderr = client.exec_command('mysql -upi -p123456') # stdout 为正确输出,stderr为错误输出,同时是有1个变量有值 # 打印执行结果 print (stdin.write('ls')) print(stdout.read().decode('utf-8')) print(stderr.read().decode('utf-8')) # 关闭SSHClient client.close()
通过netmiko
from netmiko import ConnectHandler for i in range(20,24): SW={ 'device_type':'huawei', 'ip':'10.0.1.'+str(i), 'username':'python', 'password':'123456', } connect=ConnectHandler(**SW) print('\n'+'-----------------'+'成功登录到交换机'+SW['ip']+'-----------------') config_commands=['stp mode stp','dis stp | include CIST Global Info'] output=connect.send_config_set(config_commands) print(output) connect.save_config()