利用paramiko模块模拟ssh执行命令(明文用户名密码):
import paramikossh = paramiko.SSHClient() #创建ssh对象ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy) #当找不到验证时自动添加ssh.connect(hostname='192.168.1.104',port=22,username='songsa',password='123456') #连接服务器data = input('>>>')std_in,std_out,std_err = ssh.exec_command(data) #执行命令out,err = std_out.read(),std_err.read()result = out if out else err #如果执行正确 result= stdout.read(),否则 result= stderr.read()print(result.decode())
利用paramiko模块模拟ftp来上传下载(明文用户名密码):
import paramikotransport = paramiko.Transport(('192.168.1.104',22)) #创建实例transport.connect(username='root',password='123456') #建立连接sftp = paramiko.SFTPClient.from_transport(transport) #将创建的实例当作参数传给paramiko.SFTPClient.from_transport,交互实在这里边进行的sftp.put(r'C:\Users\songsa\Desktop\python.tgz','/home/songsa/python_test/python.tgz') #上传sftp.get('/home/songsa/python_test/python.tgz',r'C:\Users\songsa\Desktop\python.tgz') #下载transport.close()
利用paramiko模块模拟ssh执行命令(基于公钥):
import paramikoprivate_key = paramiko.RSAKey.from_private_key_file(r'C:\Users\songsa\PycharmProjects\untitled\3.21\id_rsa')ssh = paramiko.SSHClient() #创建SSH对象ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy) #允许连接不在know_hosts文件中的主机ssh.connect(hostname='192.168.1.104',port=22,username='songsa',pkey=private_key)#连接服务器stdin,stdout,stderr = ssh.exec_command('pwd') #执行命令result = stdout.read()print(result.decode())ssh.close()
利用paramiko模块模拟ftp来上传下载(基于公钥):
import paramikoprivate_key = paramiko.RSAKey.from_private_key_file(r'C:\Users\songsa\PycharmProjects\untitled\3.21\id_rsa')transport = paramiko.Transport(('172.20.0.158', 22))transport.connect(username='songsa', pkey=private_key)sftp = paramiko.SFTPClient.from_transport(transport)sftp.get('/home/songsa/.ssh/id_rsa','id_rsa.txt')transport.close()