一、程序说明
ssh客户端实现主要有以下四个问题:
第一个问题是在python中ssh客户端使用哪个包实现----我们这里使用的是paramiko
第二个问题是怎么连接服务器----连接服务器直接使用connect()函数就可以了,有个坑是不在known_hosts文件中的机器默认不允许连接需要处理一下
第三个问题是连上之后怎么执行命令----连上之后直接用exec_command()函数就可以执行命令
第四个问题是怎么读取命令执行结果----exec_command()函数会返回函数执行结果,用一个参数接收一下就可以了
我们这里整个整序的流程是:
使用用户名密码登录主机----如果登录成功则执行whoami命令----打印whoami命令结果----退出ssh会话
二、程序源代码
import logging
import sys
from paramiko import AuthenticationException
from paramiko.client import SSHClient, AutoAddPolicy
from paramiko.ssh_exception import NoValidConnectionsError
class MySshClient():
def __init__(self):
self.ssh_client = SSHClient()
# 此函数用于输入用户名密码登录主机
def ssh_login(self,host_ip,username,password):
try:
# 设置允许连接known_hosts文件中的主机(默认连接不在known_hosts文件中的主机会拒绝连接抛出SSHException)
self.ssh_client.set_missing_host_key_policy(AutoAddPolicy())
self.ssh_client.connect(host_ip,port=22,username=username,password=password)
except AuthenticationException:
logging.warning('username or password error')
return 1001
except NoValidConnectionsError:
logging.warning('connect time out')
return 1002
except:
logging.warning('unknow error')
print("Unexpected error:", sys.exc_info()[0])
return 1003
return 1000
# 此函数用于执行command参数中的命令并打印命令执行结果
def execute_some_command(self,command):
stdin, stdout, stderr = self.ssh_client.exec_command(command)
print(stdout.read().decode())
# 此函数用于退出登录
def ssh_logout(self):
logging.warning('will exit host')
self.ssh_client.close()
if __name__ == '__main__':
# 远程主机IP
host_ip = '192.168.220.129'
# 远程主机用户名
username = 'root'
# 远程主机密码
password = 'toor'
# 要执行的shell命令;换成自己想要执行的命令
# 自己使用ssh时,命令怎么敲的command参数就怎么写
command = 'whoami'
# 实例化
my_ssh_client = MySshClient()
# 登录,如果返回结果为1000,那么执行命令,然后退出
if my_ssh_client.ssh_login(host_ip,username,password) == 1000:
logging.warning(f"{host_ip}-login success, will execute command:{command}")
my_ssh_client.execute_some_command(command)
my_ssh_client.ssh_logout()
参考:
http://docs.paramiko.org/en/2.4/api/client.html