How to run multiple Putty commands from Notepad - python

I have created Python TkInter to open a Putty session as below
# If the server name is not empty, open an SSH connection using PuTTY
if server_name:
#set the putty path
putty_path = 'C:\\Program Files\\PuTTY\\putty.exe'
check_db_type = db_type.get().lower()
check_db_type_action = get_action().lower()
abs_path = resource_path(f"sudo\\{check_db_type}\\{check_db_type}_sudo.txt")
# THIS IS WHAT STARTS THE SSH PUTTY SESSION
server_command = f'{putty_path} -ssh {username}#{server_name} -pw {password} -m "{abs_path}" -t'
subprocess.Popen(server_command)
# close the subprocess if it is already running and open a new subprocess
# with contextlib.suppress(Exception):
# subprocess.Popen.terminate()
# subprocess.Popen(server_command)
else:
window.destroy()
I am passing the notepad filepath in the server_command. The file contains these commands.
sudo su - postgres works well but other commands are not working
sudo su - postgres || df -kh
I have tried 3 variants of command separation as below but nothing works
sudo su - postgres; df -kh
sudo su - postgres && df -kh
sudo su - postgres
df -kh
Is there any other way to run multiple commands like these apart from using a text file? Thank you so much
I have tried to separate the 2 commands in the notepad in 3 different ways but only the first command <sudo su - postgres> is working. The next command <df -kh>, shows filesystem space, is not working as expected
I am using Windows on my laptop but access database servers through Putty remotely
++Update
When my team login as ADM (ADM account for users) and then sudo su - username, it opens a different subshell than the previous one. Can check by echo $$.
To put it simply, ADM is parent shell and sudo su - username will open child shell. After sudo su - postgres, all my following commands <uptime; df -kh, etc> running in parent shell in the background. Until I exit sudo su - postgres <CTRL + D> I cannot see the output.

Related

How do we run tmux from ssh agent using python

how do we create a tmux session using python based ssh client programs?
from pssh.clients import ParallelSSHClient
def Estabish_Connection(host,username,passkey):
client = ParallelSSHClient([str(host)],user=str(username), password=str(passkey))
return client
client2 = Estabish_Connection('host','root','password')
cmd_out = client2.run_command('tmux new -s myname')
for host,out in cmd_out.items():
for line in out.stdout:
print(line)
It doesn't create a tmux window on checking manually from a terminal.
> tmux ls
no server running on /tmp/tmux-0/default
open terminal failed: not a terminal
Okay well post the tmux bits of the script, by default it will try to attach to the current tty (which doesn't exist hence the error) if you have a new session in there for example you'll need to add a -d param to prevent this
tmux new-session -s username -d

Starting ngrok and python app on startup

I am currently running ngrock and a python app concurrently on a specific port to text my raspberry pi, and have it respond accordingly to my message via Twilio. Each time my raspberry pi boots up, or reboots, I need to manually start the services again with ./ngrok http 5000 and python /path/to/file/app.py. To avoid that, I edited my cron jobs as follows, and wrote a script called startService.py. However, it doesn't seem to be functioning properly, as I do not receive answers to texts after reboot. Any ideas?
Cron:
# m h dom mon dow command
*/5 * * * * python /rasp/system/systemCheck.py
#reboot python /Rasp/system/twilio/startService.py &
startService.py
import os
os.system('/./ngrok http -subdomain=ABC123 5000')
os.system('python /Rasp/system/twilio/starter/app.py')
You did not mention your OS, assuming your OS using Upstart for boot you can create upstart script to start then your process will automatically spawn at boot or when the process die. For ngrok, create a file /etc/init/ngrok.conf
# Ngrok
#
# Create tunnel provided by ngrok.io
description "Ngrok Tunnel"
start on runlevel [2345]
stop on runlevel [!2345]
respawn
respawn limit 10 5
umask 022
exec /ngrok http -subdomain={{My Reserved Subdomain}} 5000
Now it will automaticlaly start at boot. If you want to start manually just issue command.
$ sudo service ngrok start
Just for suggestion, putting your binary on root directory / is not good practice.
Reference:
http://notes.rioastamal.net/2016/05/starting-ngrok-automatically-at-boot.html
After multiple failed attempts I have seem to come up with a working system. I first had to authorize the root user to use my ngrok account by doing the following:
sudo su
./ngrok authtoken {{Insert Your Auth Token Here}}
exit
Then, I created ngrokLauncher.sh and appLauncher.sh as shown.
ngrokLauncher.sh:
#!/bin/sh
# launcher.sh
cd /
./ngrok http -subdomain={{My Reserved Subdomain}} 5000 &
cd /
appLauncher.sh:
#!/bin/sh
# launcher.sh
cd /Storage/system/twilio/starter
python app.py &
cd /
Then, I modified the file permissions so they would be able to be run on startup sudo chmod 755 ngrokLauncher.sh && sudo chmod 755 appLauncher.sh. Lastly, I edited the Cron Jobs as follows:
Crontab:
# m h dom mon dow command
*/5 * * * * python /SKYNET/system/systemCheck.py
#reboot sh /Storage/ngrokLauncher.sh >/Storage/logs/cronlog 2>&1
#reboot sh /Storage/appLauncher.sh >/Storage/logs/cronlog 2>&1
Then after running sudo reboot, the system restarted and I received a response to my sms from the python app.

Python fabric unable to start process

I'm using python fabric to deploy binaries to an ec2 server and am attempting to run them in background (a subshell).
All the fabric commands for performing local actions, putting files, and executing remote commands w/o elevated privileges work fine. The issue I run into is when I attempt to run the binary.
with cd("deploy"):
run('mkdir log')
sudo('iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080', user="root")
result = sudo('./dbserver &', user="root") # <---- This line
print result
if result.failed:
print "Running dbserver failed"
else:
print "DBServer now running server" # this gets printed despite the binary not running
After I login to the server and ps aux | grep dbserver nothing shows up. How can I get fabric to execute the binary? The same command ./dbserver & executed from the shell does exactly what I want it to. Thanks.
This is likey reated to TTY issues, and/or that you're attempting to background a process.
Both of these are discussed in the FAQ under these two headings:
http://www.fabfile.org/faq.html#init-scripts-don-t-work
http://www.fabfile.org/faq.html#why-can-t-i-run-programs-in-the-background-with-it-makes-fabric-hang
Try making the sudo like this:
sudo('nohup ./dbserver &', user=root, pty=False)

Execute remote commands as root using Python and paramiko

Currently I'm working on a Python script to run embed shell scripts, the OS contain root and normal_user.
The problem is, when I try to switch from normal_user to root, using a single command in one line.
I have to only modify the code and nothing like visudo to achieve this and use su only without giving the normal_user any rights outside the coding .
How can I achieve this?
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('172.16.x.x', username='my_name', password='my_password')
***stdin, stdout, stderr = ssh.exec_command('switch to root user && execute a commands as root')***
stdin.flush()
print stdout.readlines()
ssh.close()
Assuming the OS environment has sudo command installed and normal_user is allowed to sudo to root without a password:
stdin, stdout, stderr = ssh.exec_command('sudo -i -H -- echo $USER ; echo $USER')
Options -i simulators root login (prepares .profile, etc. environment variables), option -H sets the $HOME directory the same as the root. These may or may not be necessary depending on your use case.
echo $USER example shows that you are executing that command as root (it should return $USER = root).
As a security measurement you can set the normal_user to have sudo rights only if the user logs in with a correct SSH key.
http://www.evans.io/posts/ssh-agent-for-sudo-authentication/ (complex)

Running fabric scripts as root

I am trying to use fabric to automate some administrative work that I am doing on a couple of servers. The general flow is the following:
SSH with local user
run: sudo su - to become root (providing local user password again)
Do the work as root :)
Unfortunately using run('sudo su -') blocks execution of the scripts and allows user input. When I type exit or Ctrl+D the scipt resumes, but without root privileges.
I have seen a similar problem in Switching user in Fabric but I am restricted to sudo su - because I am not allowed to change the /etc/sudoers file which contains the following line:
localuser ALL = /usr/bin/su -
I browsed the source of fabric trying to find a workaround but with no success.
Having faced the same problem as yours, (only sudo su - user allowed by admin, sudo -u user -c cmd not allowed), here's my working solution with fabric:
from ilogue.fexpect import expect, expecting, run
def sudosu(user, cmd):
cmd += ' ;exit'
prompts = []
prompts += expect('bash', cmd)
prompts += expect('assword:', env.password)
with expecting(prompts):
run('sudo su - ' + user)
def host_type():
sudosu('root', 'uname -s')
There are several solutions for your issue. First, you want to run commands using sudo. You can use the fabric method sudo instead of run that runs a shell command on a remote host, with superuser privileges(sudo ref).
For example, these commands are executed using sudo :
sudo("~/install_script.py")
sudo("mkdir /var/www/new_docroot", user="www-data")
sudo("ls /home/jdoe", user=1001)
result = sudo("ls /tmp/")
Another idea is that you want to wrap a set of commands (that need to be sudoed).
You can use Fabric context managers (ref) to do that. Particularly, you can use prefix or settings.
For example:
with settings(user='root'):
run('do something')
run('do another thing')
will ask you once the root password then execute commands as root.
You can tweek settings to store the password.
There is one solution for the following problem Sorry, user localuser is not allowed to execute '/usr/bin/su - -c /bin/bash -l -c pwd' as root on hostname.
You can try sudo('mkdir ~/test_fabric',shell=False). Using param shell to avoid the bash param -l.

Categories