1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Python—实现ssh客户端(连接远程服务器)

Python—实现ssh客户端(连接远程服务器)

时间:2021-07-20 12:02:42

相关推荐

Python—实现ssh客户端(连接远程服务器)

paramiko是一个基于SSH用于连接远程服务器并执行相关操作(SSHClient和SFTPClinet,即一个是远程连接,一个是上传下载服务),使用该模块可以对远程服务器进行命令或文件操作,值得一说的是,fabric和ansible内部的远程管理就是使用的paramiko来实现的。

Paramiko模块是基于Python实现的SSH远程安全连接,用于SSH远程执行命令、文件传输等功能。

默认Python没有自带,需要手动安装:pip install paramiko。如果安装失败,可以尝试yum安装:yum install python-paramiko。

除了Paramiko模块,还有相同作用的fabric和pexpect模块。

SSH客户端实现方案一,远程执行命令(密码认证)

# -*- coding:utf-8 -*-import paramiko # 先安装pycrypto,再安装paramiko# 创建SSH对象ssh = paramiko.SSHClient()# 允许连接不在~/.ssh/known_hosts文件中的主机ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())# 连接服务器ssh.connect(hostname="106.15.88.182", port=22, username="root", password="123456")# 执行命令,不要执行top之类的在不停的刷新的命令(可以执行多条命令,以分号来分隔多条命令)# stdin, stdout, stderr = ssh.exec_command("cd %s;mkdir %s" % ("/www/wwwroot", "aa"))stdin, stdout, stderr = ssh.exec_command("python /www/wwwroot/test.py")stdin.write("终端等待输入...\n") # test.py文件有input()函数,如果不需要与终端交互,则不写这两行stdin.flush()# 获取命令结果res, err = stdout.read(), stderr.read()result = res if res else errres = result.decode()res = result.decode("utf-8")res = result.decode(encoding="utf-8")print res# 关闭服务器连接ssh.close()

SSH客户端实现方案二,远程执行命令(密码认证)

import paramikotransport = paramiko.Transport(("106.15.88.182", 22))transport.connect(username="root", password="123456") # 建立连接# transport.connect(username="root", password="口令", hostkey="密钥")# 创建SSH对象,SSHClient是定义怎么传输命令、怎么交互文件ssh = paramiko.SSHClient()ssh._transport = transport# 执行命令,不要执行top之类的在不停的刷新的命令stdin, stdout, stderr = ssh.exec_command("df")# 获取命令结果res, err = stdout.read(), stderr.read()result = res if res else errprint result.decode()# 关闭服务器连接transport.close()

SSH客户端实现方案三,远程执行命令(密码认证)

import paramikoclient = paramiko.SSHClient() # 创建SSH对象client.set_missing_host_key_policy(paramiko.AutoAddPolicy())# 允许连接不在known_hosts文件中的主机# 连接服务器,以用户名和密码进行认证client.connect(hostname="106.15.88.182", port=22, username="root", password="123456")#实例化Transport,并建立会话Sessionssh_session = client.get_transport().open_session()if ssh_session.active:ssh_session.exec_command("df")print ssh_session.recv(1024)# 关闭服务器连接client.close()

SSH客户端实现方案四,远程执行命令(密钥认证)

import paramikossh = paramiko.SSHClient()# 创建SSH对象ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 允许连接不在know_hosts文件中的主机#这里写我们的密钥文件private_key = paramiko.RSAKey.from_private_key_file("key.poem")# 连接服务器,这里我们用pkey参数设置为私钥登陆ssh.connect(hostname="106.15.88.182", port=22, username="root", pkey=private_key)stdin, stdout, stderr = ssh.exec_command('df') # 执行命令res, err = stdout.read(), stderr.read()# stdout.readline()result = res if res else errprint result.decode()ssh.close() # 关闭连接

封装之后的使用

import sys,loggingfrom paramiko.client import SSHClient, AutoAddPolicyfrom paramiko import AuthenticationExceptionfrom paramiko.ssh_exception import NoValidConnectionsErrorclass SshClient():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 1001except NoValidConnectionsError:logging.warning('connect time out')return 1002except:print("Unexpected error:", sys.exc_info()[0])return 1003return 1000def execute_some_command(self, command):stdin, stdout, stderr = self.ssh_client.exec_command(command)print stdout.read().decode()def ssh_logout(self):self.ssh_client.close()if __name__ == "__main__":command = "whoami" # 自己使用ssh时,命令怎么敲的command参数就怎么写ssh = SshClient()if ssh.ssh_login(host_ip="106.15.88.188", username="root", password="abc0506") == 1000:ssh.execute_some_command(command)ssh.ssh_logout()

python的paramiko模块 - breezey - 博客园

Python运维自动化开发之Paramiko模块_cc297322716的专栏-CSDN博客_paramiko walk

/article/125681.htm

python3+paramiko实现ssh客户端 - 诸子流 - 博客园

另一个封装好的远程连接的组件,代码如下:

#!/usr/bin/env python# coding:utf-8'''@file: SSHClient.py@attention: ssh客户端使用@desc:'''import paramikofrom paramiko.py3compat import uimport timeclass SSHClient(object):'''@attention: 关闭 ssh 链接@param ssh: ssh链接'''def close(self, ssh):ssh.close()'''@attention: 创建 ssh 链接@param v_username: 用户名@param v_password: 密码@param v_ip: IP@param v_port: 端口号'''def sshConnection(self, v_username, v_password, v_ip, v_port=22):# 创建SSH对象ssh = paramiko.SSHClient()# 把要连接的机器添加到known_hosts文件中ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())# 连接服务器ssh.connect(hostname=v_ip, port=v_port, username=v_username, password=v_password)return ssh# endregion'''@attention: 执行单条命令@param ssh: ssh链接@param v_cmd: 需要执行的命令'''def sshExecByOne(self, ssh, v_cmd):# 执行stdin, stdout, stderr = ssh.exec_command(v_cmd)result = stdout.read()if not result:result = stderr.read()return result.decode()'''@attention: 执行命令集@param s: ssh链接@param l_cmd: 需要执行的命令集@param exec_wait: 执行命令间隔时间@param exit_wait: 退出等待时间'''def sshExecByMany(self, s, l_cmd, exec_wait, exit_wait):ssh = s.invoke_shell()# 执行for v_cmd in l_cmd:ssh.send(v_cmd)ssh.send('\n')time.sleep(exec_wait)if v_cmd=='exit':time.sleep(exit_wait)result = u(ssh.recv(9999))return resultif __name__ == '__main__':getClient = SSHClient()ssh = getClient.sshConnection('sys_admin', 'XSW@1qaz', '10.82.28.219')l_cmd = ['sudo su - ','su - oracle','sqlplus / as sysdba',u'select * from dual;','exit','df -h','exit']result = getClient.sshExecByMany(ssh, l_cmd, 1, 1)print(result)getClient.close(ssh)# getClient = SSHClient()# ssh = getClient.sshConnection('sys_admin', 'XSW@1qaz', '10.82.28.219')# result = getClient.sshExecByOne(ssh,'pwd')# print(result)# getClient.close(ssh)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。