[英]Switching to non-root user and running command in Python
我试图在我的Python脚本中切换到“ apache”用户并运行命令。 我已经尝试了许多其他答案的组合,但无法完全正常工作。 这是我尝试过的事情-
这导致我的终端挂起-
command = "sudo su - apache && touch ~/testfile.txt"
for email in emailList:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())
privatekeyfile = '/home/myuser/.ssh/id_rsa2'
username ="myuser"
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)
client.connect(hostname='123.456.11.11',username=username, pkey = mykey)
stdin, stdout, stderr = client.exec_command(command)
gracefulout = stdout.read()
print gracefulout
将命令更改为command = "sudo su - apache -c 'touch testfile.txt'"
会使它什么也不做。
像sudo -u apache; whoami
这样的变体sudo -u apache; whoami
sudo -u apache; whoami
不会输出任何内容。 subprocess.call([command], stdout=subprocess.PIPE, shell=True)
导致什么都不输出或shell挂起。
还尝试了-
ssh = subprocess.Popen(["ssh", HOST, COMMAND],
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
if result == []:
error = ssh.stderr.readlines()
print sys.stderr, "ERROR: %s" % error
else:
print result
并收到错误-
ERROR: ['usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n', ' [-D [bind_address:]port] [-e escape_char] [-F configfile]\n', ' [-I pkcs11] [-i identity_file]\n', ' [-L [bind_address:]port:host:hostport]\n', ' [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n', ' [-R [bind_address:]port:host:hostport] [-S ctl_path]\n', ' [-W host:port] [-w local_tun[:remote_tun]]\n', ' [user@]hostname [command]\n']
我如何在python中切换到其他(非root)用户并运行命令?
谢谢。
最终,我们通过运行以下命令来解决此问题-
command = 'php -r "print json_encode(array('test@test.com'));" | /usr/local/bin/drush --alias-path=/home/me/drush_aliases @'+alias+'.'+env+' --root=/var/www/html/docroot vset --format=json update_notify_emails -'
stdin, stdout, stderr = client.exec_command(command)
drushoutput = stdout.read()
print(drushoutput)
client.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.