Python paramiko模块的安装

paramiko是Python语言编写的遵循SSH2协议,支持加密和认证方式,连接远程服务器执行命令或者上传下载文件。

一、安装paramiko

pip3 install paramiko

二、使用用户名密码方式远程执行命令

import paramiko  ssh = paramiko.SSHClient()  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # 自动接受远程服务器host key  ssh.connect('127.0.0.1', 22, 'username', 'password')  # 远程主机IP、端口、用户名、密码  stdin, stdout, stderr = ssh.exec_command('df -h')  # 远程服务器要执行的命令  for line in stdout:  	print(line)  ssh.close()  # 关闭ssh连接

三、使用用户名密码方式上传或下载文件

import paramiko  t = paramiko.Transport('127.0.0.1', 22)  t.connect(username='username', password='password')  sftp = paramiko.SFTPClient.from_transport(t)  sftp.put('local_file', 'remote_folder')  t.close()
import paramiko  t = paramiko.Transport('127.0.0.1', 22)  t.connect(username='username', password='password')  sftp = paramiko.SFTPClient.from_transport(t)  sftp.get('remote_file', 'local_folder')  t.close()

四、使用ssh key方式远程执行命令(前提远程主机已经接受了你的公钥)

import paramiko    private_key_path = '/home/xxx/.ssh/id_rsa'  key = paramiko.RSAKey.from_private_key_file(private_key_path)    ssh = paramiko.SSHClient()  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  ssh.connect('127.0.0.1', 22, username='username', pkey=key)  stdin, stdout, stderr = ssh.exec_command('df')  print(stdout.read())  ssh.close()

五、使用scp方式远程执行命令

import paramiko    scp = paramiko.Transport(('127.0.0.1', 22))  scp.connect(username='username', password='password')  channel = scp.open_session()  channel.exec_command('touch hello/test.txt')  channel.close()  scp.close()