Connection ssh via python in a Windows System - python

I am a beginner in python development.
In fact , I want to make an ssh connection through a python code ,
do you have an idea?

I'd suggest using fabric module. It's rather simply to use, for example:
from fabric.api import env, run
env.host_string = 'xxx.xxx.xxx.xxx'
env.user = 'username'
env.password = 'password'
run('ls -l')
That's just a simple example, but it should get you started.

Related

How to run the python file in remote machine directory?

Details:
I am having xxx.py file in B machine.
I trying to execute that xxx.python file from A machine by using python script.
assuming you have ssh access you can use paramiko
here's an example that checks diskspace on a remote host:
import paramiko
ssh = paramiko.SSHClient()
ssh.load_host_keys('/path/to/known_hosts')
#ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
my_key = paramiko.RSAKey.from_private_key_file('/home/user/.ssh/id_rsa')
ssh.connect(HOST, username="whatever", pkey=my_key)
i, o, e = ssh.exec_command('df -h /')
print int(o.readlines()[1].split()[3].replace('G', ''))
Unless you have done something to specifically allow this, such as SSH into machine B first, you cannot do this.
That's a basic safety consideration. If any host A could execute any script on host B, it would be extremely easy to run malicious code on other machines.

fabric deploy remote - asking for password

I have windows 7
I am trying:
env.hosts = ['xxx.xx.xx.xxx', 'xxx.xx.xx.xxx', 'xxx.xx.xx.xxx']
env.user = 'root'
env.key_filename = 'C:\Users\Doniyor\Desktop\ssh\secure-life\privkey.ppk'
def dm():
app_path = '/var/www/myproj/'
env_path = '/var/www/virtualenvs/myproj'
with cd(env_path):
run('. bin/activate')
with cd(app_path):
run('git pull origin master')
run('python manage.py collectstatic --settings=myproj.settings')
run('python manage.py migrate --settings=myproj.settings')
run('touch conf/uwsgi.ini')
But it keeps asking for root password:
what is missing here? I am fighting for almost 2 days now for it..
Add that private key as an SSH key for user root on all those servers with:
ssh-copy-id root#123.45.56.78
Make sure the SSH Agent is also running. SSH Agent is what uses your private key for authentication when you try to login to a remote server using SSH. Check Running SSH Agent when starting Git Bash on Windows

Using fabric how can I supply a password for psql?

I want to be able to log in to my AWS postgres database from a remote machine. I am using the following Fabric script:
import sys
from fabric.api import env, run, abort
env.port = 123
env.use_ssh_config = True
def setuser(user):
"""Sets the ssh user for the fabric script"""
env.user = user
env.password = 'mypassword'
def setenv(server):
"""Sets the environment for the fabric script"""
env.hosts = ['staging']
def sync():
# log into AWS server
run("psql --host=staging.xxx.rds.amazonaws.com --username=x_user --port=5432 --password --dbname=x_database")
run("mypassword")
I run this Fabric script using the following command:
fab -f sync_staging.py sync --password=mypassword
This logs me into the remote machine, runs the line run("psql .... and then it prompts me for a password:
[stage] out: Password for user x_user:
Is there any way that I can supply the password (or respond to the prompt) such that it logs me in automatically?
There are 2 ways of solving this that I know of:
.pgpass password file in your home directory on remote host
PGPASSWORD env variable (set on remote host)
If you need to set an environment variable on remote host, use with shell_env(PGPASSWORD='mypassword'), Fabric docs here: fabric.context_managers.shell_env
Hope it solves your problem.

How can I log into a firewall first before running fabric commands?

I'm trying to get running a deployment file in fabric, but our appservers have a firewall before the actual servers that needs to be logged into first. How can i make fabric log into that first? i haven't been able to find and documentation on this problem.
Creating a new task and fabric role should do the trick:
from fabric.api import run, task
from fabric.decorators import roles
from fabric.state import env
env.roledefs = {"firewall": ["mybox"]}
#roles("firewall")
#task
def do_stuff_on_firewall_server():
run("some-cmd")
You can run this command pretty easily:
fab do_stuff_on_firewall_server
If I understand correctly, you cannot SSH directly into the target server, but you have to SSH into the firewall first, and then from the firewall you can SSH into the target server.
In that case, you can use Fabric's --gateway command-line option:
$ fab --gateway=firewall.company.com --hosts=server.company.com sometask
See https://fabric.readthedocs.org/en/1.7/usage/fab.html#cmdoption-g

Python subprocess on remote MS Windows host

I'm trying to run netsh command on remote windows hosts (windows domain environment with admin rights). The following code works fine on local host but I would like to run it on remote hosts as well using python.
import subprocess
netshcmd=subprocess.Popen('netsh advfirewall show rule name=\”all\”', shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE )
output, errors = netshcmd.communicate()
The problem is that I'm no sure how/what method to use to initiate the connection to remote hosts and then run the subprocess commands. I cannot use ssh or pstools and would like try to implement it using existing pywin32 modules if possible.
I have used WMI module in a past which makes it very easy to query remote host but I couldn't find any way to query firewall policies over WMI and that's why using subprocess.
First you login the remote host machine using of pxssh modules Python: How can remote from my local pc to remoteA to remoteb to remote c using Paramiko
remote login of windows:
child = pexpect.spawn('ssh tiger#172.16.0.190 -p 8888')
child.logfile = open("/tmp/mylog", "w")
print child.before
child.expect('.*Are you sure you want to continue connecting (yes/no)?')
child.sendline("yes")
child.expect(".*assword:")
child.sendline("tiger\r")
child.expect('Press any key to continue...')
child.send('\r')
child.expect('C:\Users\.*>')
child.sendline('dir')
child.prompt('C:\Users\.*>')
Python - Pxssh - Getting an password refused error when trying to login to a remote server
and send your netsh command
I will recommend using Fabric, it's a powerful python tool with a suite of operations for executing local or remote shell commands, as well as auxiliary functionality such as prompting the running user for input, or aborting execution:
install fabric : pip install fabric
write the following script named remote_cmd.py:
"""
Usage:
python remote_cmd.py ip_address username password your_command
"""
from sys import argv
from fabric.api import run, env
def set_host_config(ip, user, password):
env.host_string = ip
env.user = user
env.password = password
def cmd(your_command):
"""
executes command remotely
"""
output = run(your_command)
return output
def main():
set_host_config(argv[1], argv[2], argv[3])
cmd(argv[4]))
if __name__ == '__main__':
main()
Usage:
python remote_cmd.py ip_address username password command

Categories