一、作用
paramiko模块,基于SSH用于连接远程服务器并执行相关操作。
二、使用
SSHClient
用于连接远程服务器并执行基本命令
基于用户名密码连接:
# 建立一个sshclient对象
ssh
=
paramiko.SSHClient()
# 允许将信任的主机自动加入到host_allow 列表,此方法必须放在connect方法的前面
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 调用connect方法连接服务器
ssh.connect(hostname
=
'192.168.2.129'
, port
=
22
, username
=
'super'
, password
=
'super'
)
# 执行命令
stdin, stdout, stderr
=
ssh.exec_command(
'df -hl'
)
# 结果放到stdout中,如果有错误将放到stderr中
print
(stdout.read().decode())
# 关闭连接
ssh.close()
|
坑:开始一致正常链接,重新生成ssh-key 后,无法连接了,,也设置了ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()),最后百度找到解决办法:,在connect 的时候加入参数 allow_agent, look_for_keys 就可以了。
最终找到的解决方法很简单
ssh
.
connect
(
'localhost'
,
username
=
name
,
password
=
pw
,
allow_agent
=
False
,
look_for_keys
=
False
)
备注:
1)sftp本质实现的是单个文件的传输,如果源文件路径写的是文件夹,运行时时会直接报错,多个文件的传输只能通过循环遍历实现
2)remotepath (str) – the destination path on the SFTP server. Note that the filename should be included. Only specifying a directory may result in an error.(目的文件的路径必须包含文件名,否者会报错)
def
copy_file_to_remote(ssh, local_file, remote_file):
# 建立连接
sftp
=
paramiko.SSHClient.open_sftp(ssh)
#等价于 ssh.open_sftp(ssh) 暂不知二者在原理上有什么区别
# Copy a remote file (remotepath) from the SFTP server to the local host
#dst_file must be include filename
sftp.put(local_file, remote_file)
# Copy a local file (localpath) to the SFTP server as remotepath
sftp.close()
def
copy_file_from_remote(ssh, remote_file, local_file):
# 建立连接
sftp
=
paramiko.SSHClient.open_sftp(ssh)
# Copy a remote file (remotepath) from the SFTP server to the local host
#dst_file must be include filename
sftp.get(remote_file, local_file)
# Copy a local file (localpath) to the SFTP server as remotepath
sftp.close()
|
备注:以下方式也可以实现sftp
transport
=
paramiko.Transport((
'192.168.179.130'
,
22
))
transport.connect(username
=
'root'
,password
=
'greg311'
)
sftp
=
paramiko.SFTPClient.from_transport(transport)
#该方法与 sftp = paramiko.SSHClient.open_sftp(ssh),.分析源码可知,SSHClient.open_sftp(ssh)最终也是通过SFTPClient.from_transport(t)建立传输通道
|