sftp传送文件:
import paramiko transport = paramiko.Transport(('localhost',22)) transport.connect(username='guqing',password='sina4433') sftp = paramiko.SFTPClient.from_transport(transport) #将location.py上传至服务器/guqing/home/lib sftp.put('/home/guqing/para/lib','/home/guqing/lib') #source,remote #将远程文件下载至本地/home/guqing/test/lib sftp.get('/home/guqing/lib','/home/guqing/test/lib') #remote,local transport.close()
ssh:
import paramiko #创建SSH对象 ssh = paramiko.SSHClient() #允许连接不再know_hosts文件中的主机 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #连接服务器 ssh.connect(hostname='localhost',port=22,username='guqing',password='sina4433') #执行命令 stdin,stdout,stderr = ssh.exec_command('df') res,err = stdout.read(),stderr.read() result = res if res else err print(result.decode()) ssh.close()
基于秘钥之sftp:
import paramiko private_key = paramiko.RSAKey.from_private_key_file('/home/guqing/.ssh/id_rsa') transport = paramiko.Transport(('localhost',22)) #remote_host transport.connect(username='guqing',pkey=private_key) sftp = paramiko.SFTPClient.from_transport(transport) #将location.py上传至服务器/guqing/home/lib sftp.put('/home/guqing/para/lib','/home/guqing/lib') #source,remote #将远程文件下载至本地/home/guqing/test/lib sftp.get('/home/guqing/lib','/home/guqing/test/lib') #remote,local transport.close()
基于秘钥之ssh:
import paramiko #ssh-copy-id "-p22 guqing@10.0.0.31" #复制本地用户公钥至远程主机 private_key = paramiko.RSAKey.from_private_key_file('/home/guqing/.ssh/id_rsa') #创建SSH对象 ssh = paramiko.SSHClient() #允许连接不在know_hosts文件中的主机 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #连接服务器 ssh.connect(hostname='localhost',port=22,username='guqing',pkey=private_key) stdin,stdout,stderr = ssh.exec_command('df') res,err = stdout.read(),stderr.read() result = res if res else err print(result.decode()) ssh.close()