ssh
- 基于用户名密码连接
import paramiko
ssh = paramiko.SSHClient() # 创建SSH对象
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 允许连接不在know_hosts文件中的主机
ssh.connect(hostname='192.168.1.193',port=22,username='root',password='yibao0415')
stdin, stdout, stderr = ssh.exec_command("cd /data; pwd")
print(stdout.read().decode('utf-8'))
ssh.close()
- 基于用户名密码连接,SSHClient封装Transport
import paramiko
transport = paramiko.Transport(("192.168.1.193",22)) # 设置SSH远程主机地址和端口
transport.connect(username='root',password='yibao0415') # 设置登陆用户名和密码
ssh = paramiko.SSHClient()
ssh._transport = transport
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
stdin, stdout, stderr = ssh.exec_command('df -h; pwd')
print(stdout.read().decode())
transport.close()
ssh.close()
- 基于公钥密钥连接
import paramiko
private_key = paramiko.RSAKey.from_private_key_file('C:\\Users\\Administrator\\.ssh\\id_rsa') # 需要先建立无密码登陆
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='192.168.1.193', port=22, username='root', pkey=private_key)
stdin, stdout, stderr = ssh.exec_command('df -lh; pwd')
print(stdout.read().decode())
ssh.close()
- 基于公钥密钥连接,SSHClient封装Transport
import paramiko
private_key = paramiko.RSAKey.from_private_key_file('C:\\Users\\Administrator\\.ssh\\id_rsa') # 需要先建立无密码登陆,如没有建立,需要添加password=参数
transport = paramiko.Transport(("192.168.1.193",22))
transport.connect(username='root',pkey=private_key)
ssh = paramiko.SSHClient()
ssh._transport = transport
stdin, stdout, stderr = ssh.exec_command('df -lh; ls')
print(stdout.read().decode())
print(stderr.read().decode())
ssh.close()
SFTP
脚本sftp只满足单文件上传
import paramiko
private_key = paramiko.RSAKey.from_private_key_file('C:\\Users\\Administrator\\.ssh\\id_rsa')
transport = paramiko.Transport(('192.168.1.193',22))
transport.connect(username='root',pkey=private_key)
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put('sftp.py','/root/sftp.py') # 重复则覆盖
sftp.get('/root/sftp.py','sftp1.py')
transport.close()
sftp.close()