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()