python的ssh2模块paramiko使用su切换到root帐号

 

ssh.exec_command(cmd,bufsize,timeout) #exec_command参数使用只需要执行一次的命令,因为执行完该命令以后,shell会自动回到ssh初始连接的shell状态下,(表达不好,可以看官方文档。),stdin,out,err,对应shell下的标准输入,输出和错误。

ssh.invoke_shell() #在SSH server端创建一个交互式的shell,且可以按自己的需求配置伪终端,可以在invoke_shell()函数中添加参数配置。

def chanel_exe_cmd(ChanelSSHOb,cmd,t=0.1):
    ChanelSSHOb.send(cmd)
    ChanelSSHOb.send("\n")
    time.sleep(t)
    resp = ChanelSSHOb.recv(9999).decode("utf8")
    print("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
    print("Exec sshCmd: %s" % (cmd))
    print("--------------------")
    print("Exec Result: %s" % (resp))
    print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n")
    return resp


def creatSShConnectOb(ip_remote, port_remote, username, password):
    print('---------- start to create SSH object')
    print('Remote SSH Info:\n\'ip:%s  port:%d  username:%s  password:%s\'\n' %(ip_remote, port_remote, username, password))
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        ssh.connect(ip_remote, port_remote, username=username, password=password, timeout=60) #  timeout protection
        return ssh
    except:
        print('Warning:\nFist connect the ABC failed, now will retry!')
        ssh.connect(ip_remote, port_remote, username=username, password=password, timeout=60) #  timeout re-try
        print('Error:\nAttempt to connect ABC failed!!! Please check the IP / port/ account / password.')
    else:
        print('Info:\nConnect remote ABC success.')


if __name__ == '__main__':
    ssh = creatSShConnectOb(ABC1_ip,ABC_port,admin_user,admin_pwd)
    chanelSSHOb = ssh.invoke_shell() #建立交互式的shell

    sshCmd = 'whoami'
    chanel_exe_cmd(chanelSSHOb, sshCmd)

    sshCmd = 'ls -R -l ' + ABC_admin_remoteDir
    chanel_exe_cmd(chanelSSHOb, sshCmd)

    sshCmd = 'su'
    if chanel_exe_cmd(chanelSSHOb, sshCmd).endswith(u"Password: "):
        sshCmd = root_pwd
        chanel_exe_cmd(chanelSSHOb, sshCmd)

    sshCmd = 'whoami'
    chanel_exe_cmd(chanelSSHOb, sshCmd)

    sshCmd = r'docker ps | grep mp'
    chanel_exe_cmd(chanelSSHOb, sshCmd)

    sshCmd = 'rm -rf ' + ABC_admin_remoteDir + '*'
    chanel_exe_cmd(chanelSSHOb, sshCmd)

refrence:

http://blog.chinaunix.net/uid-429659-id-3851967.html

https://blog.csdn.net/pengwupeng2008/article/details/82218388

https://www.cnblogs.com/yangshine/p/5709510.html

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值