VSCode in WSL: how to sudo a root file so I can edit it

后端 未结 5 1689
孤独总比滥情好
孤独总比滥情好 2021-02-12 13:12

WSL v.1 -- VSCode v1.40.1 (using \'Remote - WSL\' extension 40.3)

How to open a root-owned file for edit using sudo and VSCode? (without running as root)

相关标签:
5条回答
  • 2021-02-12 13:32

    Currently, the only way I was able to achieve this was to use rmate.

    1. Install rmate on your WSL VM

    sudo wget -O /usr/bin/rmate https://raw.githubusercontent.com/aurora/rmate/master/rmate
    sudo chmod a+x /usr/bin/rmate
    

    I'm using a Debian Buster WSL here, however you can replace /usr/bin with an appropriate folder in your $PATH depending on your OS or your preference.

    2. Install the Remote VS Code plugin

    make sure the Extension is enabled on WSL: after adding the plugin.

    Here is how I configured the remote VS Code plugin

    File -> Preferences -> Settings

    3. Start the VSCode rmate server

    Press F1 and run Search for the Remote: Start Server command.

    4. Edit your privileged files

    Start your WSL instance and open a terminal. If you've done everything correctly you should be able to now edit your files with sudo priveledges in your editor, even if you are not the root user.

    sudo rmate /etc/profile.d/custom-profile.sh
    
    0 讨论(0)
  • 2021-02-12 13:33

    You can own the file you want to edit, then give it back the ownership afterwards

    sudo chown myuser /path/to/file
    code /path/to/file
    sudo chown root /path/to/file
    
    
    0 讨论(0)
  • 2021-02-12 13:36

    SSH in as root through VS Code

    Don't know if this is the best approach but it worked for me. Note that this should only be used on files that only root has access to in the first place. I think saved files will be owned by root. Use this to quickly change some settings but not to write code that can done by regular user.

    1. Install ssh-server on WSL

    sudo apt install ssh
    

    2. Allow remote login as root.

    Edit or add PermitRootLogin yes inside /etc/ssh/sshd_config

    3. Restart ssh server

    sudo service ssh stop
    sudo service ssh start
    

    4. Connect to WSL in VS Code

    Ctrl + Shift + P -> Remote SSH: Add new ssh host -> root@127.0.0.1 accept all fingerprints and stuff and you're in as root. You should be able to do anything now.

    0 讨论(0)
  • 2021-02-12 13:44

    Set environment variable:

    export VISUAL="code -nw"
    

    Then you can edit any file like this:

    sudo -e file
    

    It will automatically make a copy of file, and, when you close the editor, copy it back.

    0 讨论(0)
  • 2021-02-12 13:46

    input this in powershell and press 'Enter'

    ubuntu config --default-user root
    

    then you will login wsl with root user and you can do anything now

    0 讨论(0)
提交回复
热议问题