1

I am working on a Python script that can SSH into multiple remote CentOS machines and change the value of 'ONBOOT' from 'yes' to 'no' in '/etc/sysconfig/network-scripts/ifcfg-eth1'. I can SSH into remote machines using Paramiko with my user credentials. In order to edit the '/etc/sysconfig/network-scripts/ifcfg-eth1' file I have to become a sudo user and then only I can edit the file. The Problem I am facing with my script is I cannot login directly as a root user into CentOS. I should first login with my user credentials and Then change to root using 'sudo -s' and password. Is there any way to ssh into the remote machine with my user credentials and change to root user and edit the file.?

3
  • Why can't you just give yourself root permission on the remote machine? Or add your ssh key to the authorized keys for root? Commented Feb 4, 2018 at 17:15
  • Not to echo the previous comment, but you should just fix it so you can log in as root if that's what you need to do. A bash script would probably be simpler if all you're doing is editing one line in one fine. If you're planning on doing more complex things eventually, be wary of reinventing the wheel. There are many config management tools (Salt, Ansible, Chef, etc.) that work very well. Commented Feb 4, 2018 at 17:26
  • This post is exactly what I've been searching for for weeks. Commented Jun 23, 2018 at 0:23

1 Answer 1

2

First, make a connection using ssh.connect of paramiko and then

   import paramiko
   ssh = paramiko.SSHClient()
   ssh.connect("hostname", username = "username", password = "password")
   cmd = "echo {} | sudo -S {}".format("password", "touch /opt/giri")
   ssh.exec_command(cmd)

The logined user is a normal user with sudo permission. So first the script logins as "normal user" and then executes the command with sudo permission.

-S option of the sudo command to make sudo get the its from stdinread the password from the standard input instead of using the terminal device.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.