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.?
-
Why can't you just give yourself root permission on the remote machine? Or add your ssh key to the authorized keys for root?OneCricketeer– OneCricketeer2018-02-04 17:15:53 +00:00Commented 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.UnoriginalNick– UnoriginalNick2018-02-04 17:26:46 +00:00Commented Feb 4, 2018 at 17:26
-
This post is exactly what I've been searching for for weeks.jsung8– jsung82018-06-23 00:23:38 +00:00Commented Jun 23, 2018 at 0:23
Add a comment
|
1 Answer
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.