如何在不使用 python 登录服务器的情况下在服务器中执行迭代命令

How to execute iterective commands in the server without login into the server using python

我已经使用 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

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()`