自己封装好的远程连接的组件,后期会不断完善
1、为了更方便采集信息系统以及数据库的信息,我做了该组件
2、为了让语句执行更顺畅,位置不发生错乱,暂时采用time.sleep()的方式解决
3、对于第二点会想办法将方法完善,以希望大家多多提出宝贵建议
-
#!/usr/bin/env python
-
# coding:utf-8
-
'''
-
@author: Ryan Bai(白瑞钧)
-
@license:
-
@contact: brj880719@hotmail.com
-
@file: SSHClient.py
-
@create time: 2017/11/8 18:11
-
@desc:
-
'''
-
import paramiko
-
from paramiko.py3compat import u
-
import time
-
-
'''
-
@attention: : ssh客户端使用
-
@author: 白瑞钧
-
@param date:
-
'''
-
class SSHClient(object):
-
-
'''
-
@attention: 关闭 ssh 链接
-
@author: 白瑞钧
-
@param ssh: ssh链接
-
'''
-
def close(self, ssh):
-
ssh.close()
-
-
-
'''
-
@attention: 创建 ssh 链接
-
@author: 白瑞钧
-
@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: 执行单条命令
-
@author: 白瑞钧
-
@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: 执行命令集
-
@author: 白瑞钧
-
@param ssh: 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 result
-
-
-
if __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)
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/24851054/viewspace-2147009/
,如需转载,请注明出处,否则将追究法律责任。