fabric: connect to remote server, then execute commands after sudo su - user2 - python

I need to write a python script which must be able to connect to a remote server (to user1), execute some commands (this was easy), then it must switch to user2 through sudo su - user2, and execute some commands (the problem is here).
How can make it switch to user2 without asking me the password (I can put the password somewhere in the script), and execute commands as user2.
Thanks,

Try -S (capital "S"). Quoting the sudo man page:
-S The -S (stdin) option causes sudo to read the password from
the standard input instead of the terminal device.

Related

Getting "must be run from a terminal" when switching to root user using Paramiko module in Python

I am trying to automate a task through a Python script. The idea is to login as a regular user and then send a su command and switch to the root account.
The reason I can't directly login as root is that SSHD doesn't allow root logins.
Here's what I have:
ip='192.168.105.8'
port=22
username='xyz'
password='abc'
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)
print ("SSH connection established")
stdin,stdout,stderr=ssh.exec_command('sudo fast.sh')
outlines=stdout.readlines()
outlines+=stderr.readlines()
resp=''.join(outlines)
print(resp)
Now, I want to send the su command and echo the root password. I am aware this is not good practice but I need a quick and easy way to test this so I am OK with that.
However, when I do this
stdin,stdout,stderr=ssh.exec_command('su') and provide the password, I get an error
su: must be run from a terminal
Can some one help me to solve this.
I am running Python script on my Windows laptop to ssh into a Linux device and then switch to the root user using the su command and echo the password so that I can run other commands as root.
Thanks.
First, as you know, automating su or sudo is not the correct solution.
The correct solution is to setup a dedicated private key with only privileges needed for your task. See also Allowing automatic command execution as root on Linux using SSH.
Anyway, your command fails because sudo is configured to require an interactive terminal with requiretty option in sudoers configuration file (as a way to deter its automation).
Paramiko (correctly) does not allocate a pseudo terminal for exec channel by default.
Either remove the requiretty option.
If you cannot remove it, you can force Paramiko to allocate pseudo terminal using get_pty parameter of exec_command method:
ssh.exec_command('sudo fast.sh', get_pty=True)
But that's not a good option, as it can bring you lot of nasty side effects. Pseudo terminal is intended for an interactive use, not for automating command execution. For some examples, see
Is there a simple way to get rid of junk values that come when you SSH using Python's Paramiko library and fetch output from CLI of a remote machine?
Remove of unwanted characters when I am using JSch to run command
Removing shell stuff (like prompts) from command output in JSch

Python command line call and answer

I am trying to use Gitpython in python on my virtual machine but struggle due to sudo and denied permissions etc. So instead I wanted to try a different approach. When I write sudo git pull it first asks me for the password, then for the git username, and then for the git password, what I want to do now i prefill those in some kind of os.system within python. This is what I have accomplished so far:
os.system("echo <password> | sudo -S git pull")
This solves the first problem with the sudo password. But how can I prefill answers for the questions the command line will return?
how can I prefill answers for the questions the command line will return?
By avoiding having to prefill anything.
Meaning, as root, you should be able to do a git pull without having to enter the username/password.
If you can do that as root, in a command line, you will then be able to make it work in a Python os.system("echo <password> | sudo -S git pull") call.
For that:
1/ First set the username in the remote URL itself
cd /path/to/repo
git remote -v
https://aserver/auser/arepo
git remote set-url origin https://username#aserver/auser/arepo
2/ Use a credential helper (done as root) in order for Git itself to look for the password (instead of you having to try and feed it to the command line).
Once that is working as root, repeat the same git pull in your Python program (running as root)

how to issue sudo command using python

I need to issue "sudo service nginx status" to check for service status. I have the following:
import commands
service output = commands.getoutput("sudo service nginx status")
but I am getting "no tty present and no askpass program specified"
Does someone understand this?
using commands.getoutput makes impossible to provide the user input that is required by sudo command.
The name is self explainable, you are interested only in the command output. stdin is closed.
There are several solutions for this:
Turn off the password verification for the sudo user that is launching this python script. (read about /etc/sudoers)
pipe your password: (unsafe/bad solution but easy)
"echo YOURPASS | sudo ..."
check out subprocess.popen allowing you to provide input either from console or from file
https://docs.python.org/2/library/subprocess.html#popen-constructor

Fabric: Local command usage

I want execute a command which needs sudo in local machine. So as the documentation suggests, I used the local command, but its asking me to enter the password. How can I avoid this? Is there some place where I can save my local machine password?
local('sudo /etc/init.d/tomcat6 start',capture=True)
If you do not plan to share the fabfile you can use:
echo "password\n" | sudo -S /etc/init.d/tomcat6 start
according to the sudo man page:
The -S (stdin) option causes sudo to read the password from
the standard input instead of the terminal device. The
password must be followed by a newline character.
Check the visudo command, which will allow you to edit the /etc/sudoers file, in which you can define users, commands and password-requirements on a machine (e.g. user mlzboy does not need to enter password in order to execute /etc/init.d/tomcat6). Don't forget this can create a security problem.
Sudoers manual
If you want to use sudo but on the loopback ip:
from fabric.api import sudo,env
env.hosts =['127.0.0.1']
sudo('aptitude search fabric')
No need to edit sudoers, given you have an ssh server running locally.

Cannot write a script to "svn export" in Python

I would like to write a script that will tell another server to SVN export a SVN repository.
This is my python script:
import os
# svn export to crawlers
for s in ['work1.main','work2.main']:
cmd = 'ssh %s "cd /home/zes/ ; svn --force export svn+ssh://174.113.224.177/home/svn/dragon-repos"' % s
print cmd
os.system(cmd)
Very simple. It will ssh into work1.main, then cd to a correct directory. Then call SVN export command.
However, when I run this script...
$ python export_to_crawlers.py
ssh work1.main "cd /home/zes/ ; svn --force export svn+ssh://174.113.224.177/home/svn/dragon-repos"
Permission denied, please try again.
Permission denied, please try again.
Permission denied (publickey,gssapi-with-mic,password).
svn: Connection closed unexpectedly
ssh work2.main "cd /home/zes/ ; svn --force export svn+ssh://174.113.224.177/home/svn/dragon-repos"
Host key verification failed.
svn: Connection closed unexpectedly
Why do I get this error and cannot export the directory? I can manually type the commands in the command line and it will work. Why can't it work in the script?
If I change to this...it will not work. and instead, nothing will happen.
cmd = 'ssh %s "cd /home/zes/ ;"' % s
This is a problem with SSH.
Permission denied, please try again.
This means that ssh can't login. Either your ssh agent doesn't have the correct key loaded, you're running the script as a different user or the environment isn't passed on correctly. Check that the variables SSH_AUTH_SOCK and SSH_AGENT_PID are passed to the subprocess of your python script.
Host key verification failed.
This error means that the remote host isn't known to ssh. This means that the host key is not found in the file $HOME/.ssh/known_hosts. Again, make sure that you're checking the home directory of the effective user of the script.
[EDIT] When you run the script, then python will become the "input" of ssh: ssh is no longer connected to a console and will ask python for the password to login. Since python has no idea what ssh wants, it ignores the request. ssh tries three times and dies.
To solve it, run these commands before you run the Python script:
eval $(ssh-agent)
ssh-add path-to-your-private-key
Replace path-to-your-private-key with the path to your private key (the one which you use to login). ssh-add will ask for your password and the ssh-agent will save it in a secure place. It will also modify your environment. So when SSH runs the next time, it will notice that an ssh agent is running and ask it first. Since the ssh-agent knows the password, ssh will login without bothering Python.
To solve the second issue, run the second ssh command manually once. ssh will then add the second host to its files and won't ask again.
[EDIT2] See this howto for a detailed explanation how to login on a remote server via ssh with your private key.
I guess that it is related to ssh. Are you using a public key to automatically connect. I think that your shell knows this key but it is not the case of python.
I am not sure but it's just an idea. I hope it helps
Check out the pxssh module that is part of the pyexpect project:
https://pexpect.readthedocs.org/en/latest/api/pxssh.html
It simplifies dealing with automating ssh-ing into machines.

Categories

Resources