Python-paramiko模块简单应用(给服务器上传文件或下载文件)
应用一:连接远程机执行bash命令
import paramiko#此模块用于连接虚拟机,ansible底层用此模块 hostname = '192.168.254.24' port = 22 username = 'root' password = 'root' ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())#忽略know_hosts文件 ssh.connect(hostname=hostname,port=port,username=username,password=password) while True: cmd = input('====>:') stdin, stdout, stderr = ssh.exec_command(cmd) print(stdout.read().decode('utf-8')) 或 import paramiko gannimeide = paramiko.SSHClient() gannimeide.set_missing_host_key_policy(paramiko.AutoAddPolicy()) gannimeide.connect('192.168.206.140',22,'root','123456') # stdin, stdout, stderr = gannimeide.exec_command('ls')#执行单个bash命令 # print(stdout.read().decode('utf-8')) while True: cmd = input('===>:') stdin, stdout, stderr = gannimeide.exec_command(cmd) print(stdout.read().decode('utf-8'))
应用二:连接远程机上传下载文件
import paramiko hostname = '192.168.206.140' port = 22 username = 'root' password = '123456' t=paramiko.Transport((hostname,port))#ftp t.connect(username=username,password=password) sftp = paramiko.SFTPClient.from_transport(t) sftp.put(r'C:\Users\yhy\Desktop\1.txt', '/root/chedan') sftp.get('/root/chedan',r'C:\Users\yhy\Desktop\made.txt' ) sftp.close() 或 import paramiko nimei = paramiko.Transport(('192.168.206.140',22)) nimei.connect(username='root',password='123456') p = paramiko.SFTPClient.from_transport(nimei) p.put(r'C:\Users\yhy\Desktop\1.txt', '/root/chedan2')#上传文件到远程机 p.get('/root/chedan2', r'C:\Users\yhy\Desktopmade.txt')#从远程机上下载 p.close()
import paramiko hostname = '172.16.0.136' #服务器ip port = 22 username = 'root' #服务器用户名 password = '123456' #服务器用户登录密码 t = paramiko.Transport((hostname,port)) t.connect(username=username,password=password) sftp = paramiko.SFTPClient.from_transport(t) sftp.put(r'G:\宏福课件\lnmp1.5-full.tar.gz', '/root/lnmp1.5-full.tar.gz') sftp.close()