添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
import paramiko
def switch_user(hostname, username, password, new_username, new_password):
    # 创建SSH客户端
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    # 连接SSH服务器
    client.connect(hostname, username=username, password=password)
    # 打开一个新的shell会话
    shell = client.invoke_shell()
    # 发送切换用户的命令
    shell.send(f"su - {new_username}\n")
    # 等待命令执行完成
    while not shell.recv_ready():
    # 输入新用户的密码
    shell.send(f"{new_password}\n")
    # 打印输出结果
    while shell.recv_ready():
        print(shell.recv(1024))
    # 关闭连接
    client.close()
# 使用示例
switch_user("192.168.0.1", "username", "password", "new_username", "new_password")

上述代码使用paramiko连接到SSH服务器,并通过invoke_shell()方法进入一个新的shell会话。然后,使用send()方法发送切换用户的命令(su - new_username),并使用send()方法输入新用户的密码。最后,使用recv()方法读取输出结果,并关闭SSH连接。

请注意,切换用户需要在目标服务器上已经配置了适当的权限,以允许当前用户切换到指定的新用户。