码迷,mamicode.com
首页 > 编程语言 > 详细

python 建立SSH连接发送指令

时间:2019-05-21 11:26:12      阅读:934      评论:0      收藏:0      [点我收藏+]

标签:.exe   建立   port   pytho   server   %s   服务器   发送   log   

import paramiko
import select

def link_server_client2(serverip, user, pwd):
# 进行连接
print(‘------------开始连接服务器(%s)-----------‘ % serverip)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print(‘------------开始认证......-----------‘)
client.connect(serverip, 22, username=user, password=pwd, timeout=4)
print(‘------------认证成功!.....-----------‘)
# 开启channel 管道
transport = client.get_transport()
channel = transport.open_session()
channel.get_pty()
# 执行命令nohup.log.2017-12-30
tail = ‘tail -f /app/logs/system.log‘
#将命令传入管道中
channel.exec_command(tail)
while True:
if channel.exit_status_ready():
break
try:
rl, wl, el = select.select([channel], [], [])
if len(rl) > 0:
recv = channel.recv(1024)
print(recv.decode(‘utf-8‘, ‘ignore‘))


text_save(recv.decode(‘utf-8‘, ‘ignore‘), ‘tail(‘ + serverip + ‘).txt‘)
#键盘终端异常
except KeyboardInterrupt:
print("Caught control-C")
channel.send("\x03") # 发送 ctrl+c
channel.close()
client.close()

# 文件存储
def text_save(content, filename, mode=‘a‘):

file = open(filename, mode)

for i in content:

file.write(i.encode("utf-8"))
file.close()

python 建立SSH连接发送指令

标签:.exe   建立   port   pytho   server   %s   服务器   发送   log   

原文地址:https://www.cnblogs.com/dmtz/p/10898397.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!