How to switch users in paramiko in Python?
Using the invoke_shell() method in paramiko allows for switching users by entering a new shell session and switching users by sending commands. Below is an example code:
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():
pass
# 输入新用户的密码
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")
The above code connects to an SSH server using paramiko and enters a new shell session through the invoke_shell() method. It then sends the command to switch users (su – new_username) using the send() method, followed by inputting the new user’s password using send(). Finally, it reads the output results using recv() method and closes the SSH connection.
Please note that switching users requires the target server to already have the appropriate permissions configured to allow the current user to switch to the specified new user.