How to run the python file in remote machine directory? - python

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.

Related

python script to connect to remote server and count the number of files

I have a requirement to get the number of files in the remote server thru Python.I have used the paramiko module and wrote the below script. The linux command when running in the terminal is giving me the desired output whereas when executing from Python is giving me the output as [u'0\n'].Any help is highly appreciated.
#!/usr/local/bin/python
import paramiko
client=paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('hostname', username='username')
grepCommand="ssh username#hostname 'find /usr/local/somefolder1/somefolder2 -type f -exec ls {} \;'|wc -l"
stdin,stdout,stderr = client.exec_command(grepCommand)
data=stdout.readlines()
print data
client.close()
Since the paramiko library is already making the ssh connection for you, you don't need to execute ssh in your remote command. Also it seems that you are piping the output locally into wc.. something you can't do here because with paramiko you aren't using a local shell. So:
Your grepCommand should be exactly what would work if you were to execute it in a shell on the remote machine.
eg:
find /etc -type f | wc -l

How to pass Unix Commands across network using python

So basically I have this remote computer with a bunch of files.
I want to run unix commands (such as ls or cat) and receive them locally.
Currently I have connected via python's sockets (I know the IP address of remote computer). But doing:
data = None
message = "ls\n"
sock.send(message)
while not data:
data = sock.recv(1024) <- stalls here forever
...
is not getting me anything.
There is an excellent Python library for this. It's called Paramiko: http://www.paramiko.org/
Paramiko is, among other things, an SSH client which lets you invoke programs on remote machines running sshd (which includes lots of standard servers).
You can use Python's subprocess module to accomplish your task. It is a built-in module and does not have much dependencies.
For your problem, I would suggest the Popen method, which runs command on remote computer and returns the result to your machine.
out = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
t = out.stdout.read() + out.stderr.read()
socket.send(t)
where cmd is your command which you want to execute.
This will return the result of the command to your screen.
Hope that helps !!!
This is what I did for your situation.
In terminal 1, I set up a remote shell over a socket using ncat, a nc variant:
$ ncat -l -v 50007 -e /bin/bash
In terminal 2, I connect to the socket with this Python code:
$ cat python-pass-unix-commands-socket.py
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('', 50007))
sock.send('ls\n')
data = sock.recv(1024)
print data
sock.close()
$ python pass-unix-commands-socket.py
This is the output I get in terminal 1 after running the command:
Ncat: Version 6.40 ( http://nmap.org/ncat )
Ncat: Listening on :::50007
Ncat: Listening on 0.0.0.0:50007
Ncat: Connection from 127.0.0.1.
Ncat: Connection from 127.0.0.1:39507.
$
And in terminal 2:
$ python pass-unix-commands-socket.py
alternating-characters.in
alternating-characters.rkt
angry-children.in
angry-children.rkt
angry-professor.in
angry-professor.rkt
$

Copy a directory structure including files from one remote machine to another using python

I want to copy a directory recursively from one remote machine to another remote machine with Python, probably using paramiko.
I am looking for something similar to the following scp command, but using python instead:
scp user#10.3.0.1:/path/to/file user#10.3.0.2/path/to/file
Run this command from the machine where u want to copy these file(not from source machine).
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('10.3.0.1', username='user', password='password')
stdin, stdout, stderr = client.exec_command('rsync -rav pi#10.3.0.1:path/to/file ~/')
for line in stdout:
print '... ' + line.strip('\n')
client.close()

Using fabric to copy file from one remote server to another remote server?

I need to make a service that can copy a file from one remote server to another remote server. I could just run this in a subshell:
scp user#host1:/path/to/file/video.mp4 user#host2:/path/to/file
But that doesn't seem nearly as good as using something like fabric's put command, which only copies a local file to a remote machine. I also need this to run entirely with ssh keys, no password prompting.
You can use get to get the file from host1 and then put to push it to host2.
For keys, if the private key isn't in the default location, you can specify it with the -i flag, e.g.:
fab -i /path/to/priv/key
or put it in the fabfile:
from fabric import env
env.key_filename = '/path/to/priv/key'
Also there is a possibility where agent forwarding can be used(as of fabric 1.10, with option -A). In which case you can just run the following command from host1
scp /path/to/file/video.mp4 user#host2:/path/to/file
or from host2:
scp user#host1:/path/to/file/video.mp4 /path/to/file

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