I am using spur in python to ssh into a linux server and it's doing everything I want it to, except, I am unsure of the best way to use spur to ssh into the linux server and check if a file exists on that server. I am currently doing it this way, but it is quite slow, is there a quicker way?
import spur
shell = spur.SshShell(hostname="192.168.0.22", username="username", password="password", missing_host_key=spur.ssh.MissingHostKey.accept)
inFile = "/home/myFolder/Desktop/fileNmae.avi"
try:
result = shell.run(["ls", inFile])
print "Pass"
except:
print "Fail"
You can use spurplus that we developed since we found paramiko and spur to be both a bit too low-level. Here is an example how to check if a file exists:
import spurplus
with spurplus.connect_with_retries(
hostname='some-machine.example.com', username='devop') as shell:
file_exists = shell.exists("/path/to/some/file")
pth = pathlib.Path("/path/to/another/file")
another_file_exists = shell.exists(pth)
Related
The principle of the script is that it should connect from one virtual machine to another via an SSH connection and generate a certain number of folders.
The script runs, but when executed, generates folders on the host machine.
import os
from paramiko import SSHClient, AutoAddPolicy
from sys import argv
address = argv[1]
port = int(argv[2])
name = argv[3]
path = argv[4]
prefix = argv[5]
counts = int(argv[6])
mode = int(argv[7])
def generateFolders(path, prefix, counts, mode):
for i in range(1, counts+1):
folderName = prefix + str(i)
pth = os.path.join(os.path.expanduser('~'), path, folderName)
os.mkdir(pth, mode)
command = generateFolders(path, prefix, counts, mode)
print(address)
client1 = SSHClient()
client1.set_missing_host_key_policy(AutoAddPolicy())
client1.connect(address, username=name, password='1')
stdin, stdout, stderr = client1.exec_command(command)
print(stdout.read())
client1.close()
The command in the terminal
But without a script, I can connect to another virtual machine
Jane, its making dirs on your local box because that is where the python script is running.
I suggest you look at this question and answer.
In that QandA, they show how to use ssh on the local box to execute commands on a remote box. You could use your existing code as the code which is run on the remote box using the above as your guide.
Specifically this this one
The os.mkdir creates folders on the local machine. It won't magically start working on a remote machine only because you have previous opened SSH connection to that machine (and you actually even did not, as you open it only after calling os.mkdir).
To create a folder on a remote machine via Paramiko module, use SFTPClient.mkdir.
sftp = client1.open_sftp()
for i in range(1, counts+1):
folderName = prefix + str(i)
pth = os.path.join(os.path.expanduser('~'), path, folderName)
sftp.mkdir(pth, mode)
Though you should not use os.path on SFTP paths as your code will break, if run on Windows and other platforms, that does not use / as a path separator. And os.path.expanduser will of course expand ~ to local user home. I do not think you want that.
Obligatory warning: Do not use AutoAddPolicy on its own – You are losing a protection against MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server".
I am using Fabric2 version and I don't see It has exist method in it to check if folder path has existed in the remote server. Please let me know how can I achieve this in Fabric 2 http://docs.fabfile.org/en/stable/.
I have seen a similar question Check If Path Exists Using Fabric, But this is for fabric 1.x version
You can execute the test command remotely with the -d option to test if the file exist and is a directory while passing the warn parameter to the run method so the execution doesn't stop in case of a non-zero exit status code. Then the value failed on the result will be True in case that the folder doesn't exist and False otherwise.
folder = '/path/to/folder'
if c.run('test -d {}'.format(folder), warn=True).failed:
# Folder doesn't exist
c.run('mkdir {}'.format(folder))
exists method from fabric.contrib.files was moved to patchwork.files with a small signature change, so you can use it like this:
from fabric2 import Connection
from patchwork.files import exists
conn = Connection('host')
if exists(conn, SOME_REMOTE_DIR):
do_something()
The below code is to check the existence of the file (-f), just change to '-d' to check the existence of a directory.
from fabric import Connection
c = Connection(host="host")
if c.run('test -f /opt/mydata/myfile', warn=True).failed:
do.thing()
You can find it in the Fabric 2 documentation below:
https://docs.fabfile.org/en/2.5/getting-started.html?highlight=failed#bringing-it-all-together
Hi That's not so difficult, you have to use traditional python code to check if a path already exists.
from pathlib import Path
from fabric import Connection as connection, task
import os
#task
def deploy(ctx):
parent_deploy_dir = '/var/www'
deploy_dir ='/var/www/my_folder'
host = 'REMOTE_HOST'
user = 'USER'
with connection(host=host, user=user) as c:
with c.cd(parent_deploy_dir):
if not os.path.isdir(Path(deploy_dir)):
c.run('mkdir -p ' + deploy_dir)
Objective:
I am using Ubuntu 16.04 and am using WMI-CLient-Wrapper module to connect to a remote Windows Machine and send an executable to it(eg. Process Explorer) and further execute it and collect the logs it creates and fetch them back to my Linux Machine for further processing. Using WMI CLient Wrapper is the only option available as WMI Module doesn't work with Linux.
Problem:
I am able to send the file to the remote Windows machine, by establishing a connection using WMI-Client-Wrapper and SMB File Transfer Mechanism. After that when I try to create a Process for the same and try to execute that process it gives me an error stating that some of the attributes that WMI actually has, are not supported by WMI client Wrapper.
What I tried
Python Code:
import os
import wmi_client_wrapper as wmic
from socket import *
import time
wmic = wmic.WmiClientWrapper(
host ="192.168.115.128",
username = "LegalWrongDoer",
password = "sasuke14"
)
SW_SHOWNORMAL = 1
str = "smbclient //192.168.115.128/C$ -U LegalWrongDoer%sasuke14 -c \'put \"procexp64.exe\"\'"
os.system(str)
print("Folder sent")
process_startup = wmic.Win32_ProcessStartup.new()
process_startup.ShowWindow = SW_SHOWNORMAL
process_id, result = wmic.Win32_Process.Create(CommandLine="C:/procexp64.exe", ProcessStartupInformation=process_startup)
process_startup.ShowWindow = SW_SHOWNORMAL
if result == 0:
print("Process started successfully")
else:
print("Sorry, but can't execute Process!")
When I run this python file, it gives me the output to the initial query I make. But the Process_StartUp fails.
Further Traceback Calls:
Traceback (most recent call last):
File "WMIClient.py", line 22, in <module>
process_startup = wmic.Win32_ProcessStartup.new()
AttributeError: 'WmiClientWrapper' object has no attribute 'Win32_ProcessStartup'
I'd be extremely grateful if anyone of you can be able to help me through this. Thanks in advance :)
Well I finally managed to get a work-around for this whole scenario, and it might look a little messy but it sure does work for me.
Firstly I use smbclient to transfer the executable to the end-point where I want to execute it. Inside my code I use os.system() calls to make this happen.
import os
str1 = "smbclient //'<HostMachineIP>'/admin$ -U '<domain>\\<username>%<password>' -c \'lcd /usr/local/acpl/bin/endPoint/; put \"EndPointForeignsics.exe\"\'"
os.system(str1)
This helps me put the executable in desired shared folder that the user has access(Admin in my case) to and then use WMI-query through a tool called Winexe to get access to the console/command prompt of the end-point. I use another os.system() call to execute this again.
str2 = r'/usr/local/bin/winexe -U "<domain>\\<username>%<password>" //<HostMachineIP> "cmd /c c:\windows\EndPointForeignsics.exe '
os.system(str2)
P.S:-- Winexe is a tool that you'll have to download off the internet and compile it. It may take some time and effort to do that, but is quite achievable. You'll get a lot of help on the same from StackOverflow and Documentation of the tool.
I am writing a program in python on Ubuntu, to remove a file from remote machine(raspberrypi) by accessing it, connected with network.
For file selection I am using a command called askopenfilename.
But I am struggling in specifying the Path of RaspberryPi correctly.
Can you please guide me on how do I specify Raspberrypi path correctly?
IP = "192.168.2.34"
Username = "pi"
Password ="raspberry"
Path="/home/pi/python"
Below is my code
from tkFileDialog import askopenfilename
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('192.168.2.34', username='pi', password='raspberry')
checkdir = "/home/pi/python"
name1= askopenfilename(title = "Select File For Removal", initialdir = checkdir)
stdin, stdout, stderr = client.exec_command('ls -l')
for line in stdout:
print '... ' + line.strip('\n')
client.close()
I am fairly sure the tk file dialog is only able to browse the Ubuntu machine (which it seems to run on) filesystem - not the RPi filesystem over SSH, so you will never see RPi directories.
if You can read the RPi directory listing there, so you could create your own file browser component or try to find an existing one that works over SSH.
Then again it looks like you are 'inventing the wheel again' (which of course is ok for learning purposes) - gFTP, FileZilla, many of the Linux desktop file browsers etc. (or WinSCP if you were using a Windows box) are ready made tools for this.
I m trying to use fabric module through simple python module
remoteExc.py
from fabric.api import *
def clone_repo(IPADDRESS,USER,fPath,git_url):
env.hosts_string = IPADDRESS
env.user = USER
env.key_filename = fPath
env.disable_known_hosts = 'True'
run('git clone %s' % (git_url))
mainFile.py
from remoteExc import clone_repo
clone_repo(ipAddress,user,fPath,git_url)
When i execute it says
python mainfile.py
No hosts found. Please specify (single) host string for connection:
Please enlight me where i make a mistake
Typo. env.host_string = IPADDRESS - you've got an env.hosts_string instead.
Also, generally you run fabric via fab - unless you're trying to do something fairly non-standard, be aware that running it via python probably isn't what you want to do. See the Fabric docs for a pretty good intro.
http://docs.fabfile.org/en/1.7/tutorial.html