zoukankan      html  css  js  c++  java
  • python 建立SSH连接发送指令

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

  • 相关阅读:
    素数筛的2种方法
    c++含结构体的sort()使用
    构建c++二维vector
    c语言输入单字符避免回车的四种方法
    menset()在c++中的作用
    杭电oj hud1092 1093 活用EOF&n--
    EOF在while(scanf("%d",&n))中的作用
    KMP算法
    图解HTTP(3)
    图解HTTP(2)
  • 原文地址:https://www.cnblogs.com/dmtz/p/10898397.html
Copyright © 2011-2022 走看看