使用公钥通过 ssh 登录并使用 Python 创建一个新用户? [英] Login via ssh using publickey and create a new user using Python?

查看:27
本文介绍了使用公钥通过 ssh 登录并使用 Python 创建一个新用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用私钥通过 ssh 使我的 python 脚本登录到服务器,然后使用给定的密码创建用户?我试过这段代码,但我无法像发送sudo adduser 用户名"这样更进一步

How do I make my python script login to a server thrugh ssh using a private key and then create a user using the given password? I tried this code but I am not able to go further like sending a "sudo adduser username"

和sudo adduser username groupname"...

and "sudo adduser username groupname"...

import paramiko
k = paramiko.RSAKey.from_private_key_file("/Users/whatever/Downloads/mykey.pem")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print "connecting"
c.connect( hostname = "www.acme.com", username = "ubuntu", pkey = k )
print "connected"
commands = [ "sudo adduser myuser" ]
for command in commands:
    print "Executing {}".format( command )
    stdin , stdout, stderr = c.exec_command(command)
    print stdout.read()
    print( "Errors")
    print stderr.read()
c.close()

请给我建议,否则我会很感激如果有人能帮助我提供一个可行的例子.

Please advise me or I would really appreciate if someone could be kind enough to help me with a working example.

谢谢

推荐答案

我已经通过运行不同的命令测试了您的代码.因此,请检查您是否能够运行诸如sudo uptime"之类的简单命令.如果一切正常,请按照以下说明进行操作.

I've tested your code by running different commands. So, please check if you are able to run simple commands like "sudo uptime". If it works fine, then follow the below instructions.

如果您运行sudo adduser myuser",系统将提示您输入更多详细信息,如下所示:

If you run "sudo adduser myuser", you will be prompted to enter more details as in below output:

sudo adduser myuser
Adding user `myuser' ...
Adding new group `myuser' (1002) ...
Adding new user `myuser' (1002) with group `myuser' ...
The home directory `/home/myuser' already exists.  Not copying from `/etc/skel'.
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
Changing the user information for myuser
Enter the new value, or press ENTER for the default
        Full Name []:
        Room Number []:
        Work Phone []:
        Home Phone []:
        Other []:
Is the information correct? [Y/n] y

因此,使用命令sudo useradd myuser"而不是sudo adduser myuser",因为useradd"命令不会提示任何输入.

So, use the command "sudo useradd myuser" instead of "sudo adduser myuser" because "useradd" command will not prompt for any inputs.

这篇关于使用公钥通过 ssh 登录并使用 Python 创建一个新用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆