溫馨提示×

python中paramiko如何切換用戶

小億
225
2024-01-03 17:35:11
欄目: 編程語言

在paramiko中切換用戶可以使用invoke_shell()方法進入一個新的shell會話,并通過發(fā)送命令來切換用戶。以下是一個示例代碼:

import paramiko

def switch_user(hostname, username, password, new_username, new_password):
    # 創(chuàng)建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()
    
    # 發(fā)送切換用戶的命令
    shell.send(f"su - {new_username}\n")
    
    # 等待命令執(zhí)行完成
    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")

上述代碼使用paramiko連接到SSH服務器,并通過invoke_shell()方法進入一個新的shell會話。然后,使用send()方法發(fā)送切換用戶的命令(su - new_username),并使用send()方法輸入新用戶的密碼。最后,使用recv()方法讀取輸出結果,并關閉SSH連接。

請注意,切換用戶需要在目標服務器上已經配置了適當的權限,以允許當前用戶切換到指定的新用戶。

0