paramiko介绍
ssh是一个协议,OpenSSH是其中一个开源实现,paramiko是Python的一个库,实现了SSHv2协议(底层使用cryptography)。
有了Paramiko以后,我们就可以在Python代码中直接使用SSH协议对远程服务器执行操作,而不是通过ssh命令对远程服务器进行操作。
paramiko属于第三方库,所以需要使用如下命令现行安装
pip install paramiko
paramiko包含了两个核心组件:SSHClient 和 SFTPClient
SSHClient的作用类似于Linux的ssh命令,是对SSH会话的封装,该类封装了传输(Transport),通道(Channel)及SFTPClient建立的方法(open_sftp),通常用于执行远程命令。
SFTPClient的作用类似与Linux的sftp命令,是对SFTP客户端的封装,用以实现远程文件操作,如文件上传、下载、修改文件权限等操作。
paramiko的几个基础名词:
1. channel: 一种类Socket,一种安全的SSH传输通道;`
2. Transport:是一种加密的会话,使用时会同步创建了一个加密的Tunnels(通道),这个Tunnels叫做Channel;
3. Session:是client与Server保持连接的对象,用connect()/start_client()/start_server()开始会话。
invoke_shell()
打开一个新的子shell进程,用来与Linux进行交互,sudo -i 切换用户不受影响
import paramiko
import time
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(hostname="250.250.250.250", port=22, username="admin", password="123")
channel = ssh.invoke_shell()
time.sleep(0.1)
channel.send("sudo -i \n") #切换
channel.send("123\n") #输入登录密码
buff = ''
while not buff.endswith('# '):
resp = channel.recv(9999)
buff += resp.decode('utf-8')
print(buff)
channel.send("ls")
channel.send('\n')
buff = ''
while not buff.endswith('# '): # 当指令执行结束后,Linux窗口会显示#,等待下条指令,所以可以用作识别全部输出结束的标志。
resp = channel.recv(9999)
buff += resp.decode('utf-8')
print(buff)
print("------end------")
# 查看是否切换成功
channel.send("whoami")
channel.send("\n")
buff = ''
while not buff.endswith('# '):
resp = channel.recv(9999)
buff += resp.decode('utf-8')
print(buff)
except paramiko.ssh_exception.AuthenticationException:
print('登录失败,IP用户名或密码错误。')
exit(-1)