简体   繁体   English

进入sudo用户,运行几个命令,使用Python脚本回到普通用户

[英]Go into sudo user, run couple of commands, go back to normal user in Python script

The problem I've run into is that I want to temporarily get into the sudo user, run a couple of commands, and then go back to a normal user and run the commands in that mode. 我遇到的问题是我想暂时进入sudo用户,运行几个命令,然后回到普通用户并以该模式运行命令。

You can find the script I'm gonna use it in here: https://github.com/Greduan/dotfiles/blob/master/scripts/symlinks.py 您可以在这里找到要使用的脚本: https : //github.com/Greduan/dotfiles/blob/master/scripts/symlinks.py

Basically, when I'm installing the scripts under the /bin folder of my dotfiles I need sudo access in order to make a symlink to that folder. 基本上,当我在dotfiles的/bin文件夹下安装脚本时,我需要sudo访问权限才能建立到该文件夹​​的符号链接。 You can find this part of the script under the last for statement in the code. 您可以在代码的最后一个for语句下找到脚本的这一部分。

However, since I do depend on some commands that use the current user as a guideline to do stuff, I can't just run the entire script as sudo . 但是,由于我确实依赖一些使用当前用户作为指导来进行操作的命令,因此我不能只将整个脚本作为sudo运行。 Last time I tried I got a lot of errors about a folder not existing. 上次尝试时,出现关于文件夹不存在的很多错误。

Thanks for all the help you can provide. 感谢您提供的所有帮助。

If you don't mind installing an external dependency, the sh module makes this pretty simple: 如果您不介意安装外部依赖项,则sh模块使此操作非常简单:

import sh

sh.cp('foo.txt', 'bar.txt')

with sh.sudo:
    sh.cp('foo2.txt', 'bar2.txt')

In the end I tried @Blender's solution, but it didn't work or I wasn't able to figure it out. 最后,我尝试了@Blender的解决方案,但是它没有用,或者我无法弄清楚。

So Instead I did the following: 因此,我做了以下工作:

subprocess.Popen('sudo rm ' + final_dest, shell=True)

and: 和:

subprocess.Popen('sudo ln -s ' + final_src + ' ' + final_dest, shell=True)

This works correctly as I expected it and it has no extra dependencies. 如我所料,它可以正常工作,并且没有额外的依赖关系。 Thanks for your answer @Blender but it didn't work for me. 感谢您的回复@Blender,但它对我不起作用。 ;| ; |

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM