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.youkuaiyun.com/pengwupeng2008/article/details/82218388

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

### Python Paramiko SSH 远程登录并切换Root 用户 为了实现通过Python使用Paramiko库进行SSH远程登录并切换Root用户,需遵循特定流程来确保操作的安全性和有效性。 首先,设置日志记录以便于后续排查可能遇到的问题。这可以通过`paramiko.util.log_to_file()`函数完成,该方法允许将调试信息保存到指定的日志文件中[^1]: ```python import paramiko # 设置日志输出路径及等级 paramiko.util.log_to_file('paramiko_root_switch.log') ``` 接着创建一个新的SSH客户端对象,并设定主机密钥策略以自动接受未知的主机公钥: ```python client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ``` 建立与目标机器的实际连接前,需要提供必要的认证参数(IP地址、端口号、用户名和密码)。这里假设已知这些细节信息: ```python hostname = 'example.com' port = 22 username = 'initial_user' # 初始登陆使用的非root账号 password = 'your_password' try: client.connect(hostname=hostname, port=port, username=username, password=password) except Exception as e: print(f"Connection Error: {e}") else: print("Connected successfully.") ``` 成功建立会话后,可通过执行命令的方式请求权限提升至超级管理员角色。通常情况下,此过程涉及输入当前用户的sudo密码或直接利用su指令加上相应的目标身份标识符(-): ```python if client.get_transport().is_authenticated(): stdin, stdout, stderr = client.exec_command('echo %s | sudo -S su -' % (password)) output = stdout.read().decode() errors = stderr.read().decode() if not errors: print("Switched to root user.") else: print(f"Failed switching users due to error(s):\n{errors}") finally: client.close() ``` 上述代码片段展示了如何借助标准输入流(stdin)传递初始用户的sudo密码给操作系统处理程序,从而获得更高权限的操作环境。需要注意的是,在实际应用环境中应当谨慎对待硬编码敏感数据的做法;考虑采用更安全的方法获取此类凭证,比如交互式提示或其他形式的身份验证机制。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值