我已经使用 paramiko 添加用户,但是 useradd 命令有效,并且 adduser 没有任何方法来提供可以提供的所有详细信息,例如密码、名字、姓氏等...
#!/usr/bin/env python
import paramiko
import subprocess
import os
import crypt
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('<hostname>', username='<username>', password='<password>', key_filename='<path/to/openssh-private-key-file>')
username = raw_input("enter the name : ")
a = stdin, stdout, stderr = ssh.exec_command( "useradd " + username )
while line == stdout.readlines():
print (line)
ssh.close()
最佳答案
sudo adduser $username 是一个交互式命令,您需要向终端提供输入。您可以使用此代码:
此代码将在后台与目标服务器的终端进行交互,并提供用户提供的所有必需输入
username = input("enter the name : ")
这作为要添加为用户的输入提供
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
output = ssh.connect('<$server-ip>', port='<$port>', username='$username',
key_filename="key/file/path")
username = input("enter the name : ")
command = f"sudo adduser {username}"
channel = ssh.invoke_shell()
channel_data = str()
password = "$password_wants_to_assign"
complete = false
while True:
if channel.recv_ready():
channel_data = channel.recv(9999).decode("utf-8")
else:
continue
if channel_data.endswith("hostname_of_targeted_server"):
if not complete:
channel.send(command)
channel.send("\n")
complete = True
else:
break
elif channel_data.endswith("UNIX password: "):
channel.send(password)
channel.send('\n')
elif channel_data.endswith("[]: "):
channel.send('\n')
elif channel_data.endswith("[Y/n] "):
channel.send("Y\n")
ssh.close()`
关于python - 如何使用python在不登录服务器的情况下在服务器中执行迭代命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58378733/