使用paramiko库ssh连接到远端云主机上时,非常偶现卡死现象,连接无法退出(可以是执行命令时云主机重启等造成)。需要给定一段时间,不管命令执行是否卡住,都退出连接,显示命令执行超时错误。
实现方式:
线程+事件,在线程中执行ssh命令,给事件配置超时时间。
代码示例:
1 from threading import Thread, Event
2 import paramiko
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
class SshClient( object ): def __init__( self , ip, port, username, password): self .ip = ip self .host = host self .username = username self .password = password def exec_command(cmd, timeout): log.info(u "在ip:%s上执行命令%s" % ( self .ip, cmd)) sc = paramiko.SSHClient() sc.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 用来接收stdout stderror status信息 res = [ None , None , None ] def get_return(start_event, res_list): _, cmd_stdout, cmd_stderr = sc.exec_command(command = cmd, timeout = timeout) channel = cmd_stdout.channel cmd_status = channel.recv_exit_status() res_list[ 0 ] = cmd_stdout res_list[ 1 ] = cmd_stderr res_list[ 2 ] = cmd_status start_event. set () # 表示线程已经执行完毕 try : sc.connect(hostname = self .ip, port = self .port, username = self .username, password = self .password, timeout = 30 ) # 这里的timeout是连接使用的,与我们要的不同 start_evt = Event() t = Thread(target = get_return, args = (start_evt, res)) t.start() start_evt.wait(timeout = timeout) # 执行到这里说明线程已经退出 if None in res: raise Exception(u "命令超时退出" ) stdout, stderr, status = res if status ! = 0 : raise Exception(u "命令执行返回非0!返回值为%s,错误信息为%s" % (status, stdout.read() + stderr.read())) return stdout.read() + stderr.read() finally : sc.close() } |
知识点补充:
python paramiko的使用介绍
一: 使用paramiko
#设置ssh连接的远程主机地址和端口
t=paramiko.Transport((ip,port))
#设置登录名和密码
t.connect(username=username,password=password)
#连接成功后打开一个channel
chan=t.open_session()
#设置会话超时时间
chan.settimeout(session_timeout)
#打开远程的terminal
chan.get_pty()
#激活terminal
chan.invoke_shell()
然后就可以通过chan.send('command')和chan.recv(recv_buffer)来远程执行命令以及本地获取反馈。
二: paramiko的两个模块介绍
paramiko有两个模块SSHClient()和SFTPClient()
SSHClient()的使用代码:
1
2
3
4
5
6
7
8
9
10
11
12
|
import paramiko ssh = paramiko.SSHClient() # 创建SSH对象 # 允许连接不在know_hosts文件中的主机 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 连接服务器 ssh.connect(hostname = '192.168.2.103' , port = 22 , username = 'root' , password = '123456' ) stdin, stdout, stderr = ssh.exec_command( 'ls' ) # 执行命令 result = stdout.read() # 获取命令结果 print ( str (result,encoding = 'utf-8' )) ssh.close() # 关闭连接 |
SSHClient()里有个transport变量,是用于获取连接,我们也可单独的获取到transport变量,然后执行连接操作
1
2
3
4
5
6
7
8
9
10
11
12
|
import paramiko transport = paramiko.Transport(( '192.168.2.103' , 22 )) transport.connect(username = 'root' , password = '123456' ) ssh = paramiko.SSHClient() ssh._transport = transport stdin, stdout, stderr = ssh.exec_command( 'df' ) print ( str (stdout.read(),encoding = 'utf-8' )) transport.close() |
用transport实现上传下载以及命令的执行:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
#coding:utf-8 import paramiko import uuid class SSHConnection( object ): def __init__( self , host = '192.168.2.103' , port = 22 , username = 'root' ,pwd = '123456' ): self .host = host self .port = port self .username = username self .pwd = pwd self .__k = None def connect( self ): transport = paramiko.Transport(( self .host, self .port)) transport.connect(username = self .username,password = self .pwd) self .__transport = transport def close( self ): self .__transport.close() def upload( self ,local_path,target_path): # 连接,上传 # file_name = self.create_file() sftp = paramiko.SFTPClient.from_transport( self .__transport) # 将location.py 上传至服务器 /tmp/test.py sftp.put(local_path, target_path) def download( self ,remote_path,local_path): sftp = paramiko.SFTPClient.from_transport( self .__transport) sftp.get(remote_path,local_path) def cmd( self , command): ssh = paramiko.SSHClient() ssh._transport = self .__transport # 执行命令 stdin, stdout, stderr = ssh.exec_command(command) # 获取命令结果 result = stdout.read() print ( str (result,encoding = 'utf-8' )) return result ssh = SSHConnection() ssh.connect() ssh.cmd( "ls" ) ssh.upload( 's1.py' , '/tmp/ks77.py' ) ssh.download( '/tmp/test.py' , 'kkkk' ,) ssh.cmd( "df" ) ssh.close() |
到此这篇关于使paramiko库执行命令时,在给定的时间强制退出的文章就介绍到这了,更多相关paramiko库执行命令内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://www.cnblogs.com/qiuqiuwu/archive/2021/03/02/14468981.html