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

标签 python ssh paramiko

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

相关文章:

python - 什么是 julia 中的 ".=="以及它在 python 中的等价物?

python - 无法使用 paramiko 查看 ifconfig 输出

ansible - 如何在ansible中沉默paramiko CryptographyDeprecationWarnings

python - 如何在 paramiko 中写入标准输入(从 exec_command 返回)?

python - 在具有常量但不可散列对象的函数上使用 functools.lru_cache

python: 基于字典的分词

python - python中的时间分析

ssh - SSHv2 DH key 交换中的大安全素数

python - Paramiko Python : IOError: [Errno 13] Permission denied

java - selenium 服务器,selenium 客户端,在 UBUNTU GUI 服务器上