簡體   English   中英

切換到非root用戶並在Python中運行命令

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM