• pyhon项目之后pexpect使用


    pyhon项目之后pexpect使用
    1.安装
    pip3.6 install pexpect

    实例1 ssh 登陆linux 服务器,并且执行命令

    #!/usr/bin/env python3.6
    # -*- coding: utf-8 -*-
    # @Time : 2019/10/24 17:33
    # @Author : zoulixiang
    # @Site :
    # @File : ssh_login_password.py
    # @Software: PyCharm
    import pexpect

    def login_ssh_passwd(port="",user="",host="",passwd="",command=""):
    '''函数:用于实现pexepect实现ssh的自动化用户密码登陆'''

    #print 'ssh -p %s %s@%s' %(port, user, host)
    if port and user and host and passwd and command:
    ssh = pexpect.spawn('ssh -p %s %s@%s %s' %(port, user, host, command))
    i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5)
    if i == 0:
    ssh.sendline(passwd)
    elif i == 1:
    ssh.sendline('yes ')
    ssh.expect('password: ')
    ssh.sendline(passwd)

    index = ssh.expect(["#",pexpect.EOF, pexpect.TIMEOUT])

    if index == 0:
    print("logging in as root!")
    #执行命令
    ssh.before,ssh.after
    elif index == 1:
    print("logging in as non-root!")
    print(ssh.before)
    elif index == 2:
    print("logging process exit!")
    elif index == 3:
    print("logging timeout exit")
    else:
    print("Parameter error!")

    def login_ssh_key(keyfile="",user="",host="",port="", command=""):
    '''函数:用于实现pexepect实现ssh的自动化密钥登陆'''
    if port and user and host and keyfile and command:
    ssh = pexpect.spawn('ssh -i %s -p %s %s@%s %s '% (keyfile,port,user,host,command))
    i = ssh.expect([pexpect.TIMEOUT,'continue connecting (yes/no)?'], timeout=5)
    print("-"*10)
    print(i)
    if i == 0:
    ssh.sendline('yes ')
    index = ssh.expect(["#", pexpect.EOF, pexpect.TIMEOUT])
    else:
    index = ssh.expect(["#", pexpect.EOF, pexpect.TIMEOUT])
    print(index)

    if index == 0:
    #执行命令
    ssh.before,ssh.after
    print("logging in as root!")
    elif index == 1:
    print("logging in as non-root!")
    elif index == 2:
    print("logging process exit!")
    elif index == 3:
    print("logging timeout exit")
    else:
    print("Parameter error!")

    def main():
    '''主函数:实现两种f方法分别登陆'''
    #command = "hostname"
    #login_ssh_passwd(port='22', user='root',host='192.168.3.201',passwd='matrix@178',command='pwd')
    login_ssh_key(keyfile="/root/.ssh/id_rsa",port='22',user='root',host='192.168.3.201', command="mkdir -p /root/test2222")

    if __name__ == '__main__':
    main()

  • 相关阅读:
    SQL的各种连接(cross join、inner join、full join)的用法理解
    解决sonarQube 'Unknown': sonar.projectKey
    DOS批处理高级教程
    java自定义注解
    inode备忘
    sed备忘
    awk备忘
    Oracle 删除表中记录 如何释放表及表空间大小
    Oracle 11g 分区拆分与合并
    Maven的settings.xml文件结构之mirrors
  • 原文地址:https://www.cnblogs.com/zoulixiang/p/11737026.html
Copyright © 2020-2023  润新知