Rsync command not working with python - python

I am trying implement rsync with python. Here's my code.
#!/usr/bin/python
import os
url = raw_input("Paste your URL:")
username = raw_input("Enter username:")
#password = raw_input("Enter password:")
source = username + "#" + url
#print source
print os.system('rsync -zvr --progress source /home/zurelsoft/R')
The logic is simple: user inputs the url and username stored in source with proper formatting. The source variable is then used in rsync command. I am inputting the valid URL and username of my server but I am getting this error:
rsync: link_stat "/home/name/source" failed: No such file or directory (2)
What am I doing wrong?

You're passing a static string. Regardless of what the user inputs, you're always giving rsync the exact same commandline options. You probably want source to be replaced with the value:
print os.system('rsync -zvr --progress {source} /home/zurelsoft/R'.format(source=source))
As a side note, this can be done better with subprocess :
subprocess.call(['rsync','-zvr','--progress',source,'/home/zurelsoft/R'])
It might not matter, but you'll close a HUGE security hole in your program this way (consider if the user put ; rm -rf ~; as their username ...) and it's always a good idea practice good programming habits.

Use subprocess.call
subprocess.call(["rsync", "-avz", "--exclude-from", "/tmp/exclude-list.txt", source, destination])
or if you need out put,
output = subprocess.Popen(["rsync", "-avz", "--exclude-from", "/tmp/exclude-list.txt", source, destination])

Related

How do I use multiple variables and strings within an os.system() command?

im trying to make a simple program that downloads a file. im having a problem with the command part. here is the code:
import os
#gather user input
print("hello! welcome to the website dowloader! paste in the url(including the http
part) and type in the file name!)")
url = input("website url: ")
filename = input("the filename:")
#the command i want run. for example, if the url was "https://example.com" and the
#filename was "example.html"
#then i would want the command run to be: 'curl https://example.com --output
#example.html'
cmd = str("curl ", url," --output ", filename)
os.system(cmd)
str("curl ", url," --output ", filename) are you asking how to concatenate strings? You do that with the + operator, but usually, formatting strings would be eaiser here, so just f"curl {url} --output {filename}". Also, you should probably be using subprocess instead of os.system
answer by #juanpa.arrivillaga

How can I execute OS Commands with Python pexpect?

I want to execute a python script, which switches to another user by automatically writing the user password. Both users have no root rights. After the login I want to execute the OS Commands "whoami" to check if the login was successful. Here's the code:
child = pexpect.spawn('su - otheruser)
child.expect_exact('Password:')
child.sendline('password')
print("logged in...")
child.expect('')
child.sendline('whoami')
print(child.before)
I want to print the output from the command to the console (just for debugging) but the output is like "b272' (a combination of random letters) and not the actual whoami user. How can I fix that?
Later I want to create from the switched user some files and so on. So basically, I want to execute OS Commands in a python script which is logged in an other user.
Pexpect searches are not greedy, so it will stop at the first match. When I tested your code with before, match.groups(), after, and buffer, I didn't get an EOF or TIMEOUT, so it must have matched right at the beginning of the read and returned nothing (I'm surprised you got any results at all).
I recommend always following a sendline with an expect, and the end of a prompt (]$) is a good thing to expect, instead of an empty string.
Here is my take on your code, including creating a file:
NOTE - Tested on Centos 7.9, using Python 2.7.
import pexpect
child = pexpect.spawn("su - orcam")
child.expect_exact("Password:")
child.sendline("**********")
child.expect_exact("]$")
print("Logged in...\n")
child.sendline("whoami")
child.expect_exact("]$")
print(child.before + "\n")
child.sendline("echo -e 'Hello, world.' >> hello.txt")
child.expect_exact("]$")
child.sendline("cat hello.txt")
child.expect_exact("]$")
print(child.before + "\n")
child.sendline("exit")
index = child.expect_exact(["logout", pexpect.EOF, ])
print("Logged out: {0}".format(index))
Output:
Logged in...
whoami
orcam
[orcam#localhost ~
cat hello.txt
Hello, world.
[orcam#localhost ~
Logged out: 0

Automate the boring stuff with Python chapter 6 Password locker

#! python3
# pw.py - An insecure password locker program.
PASSWORDS = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6',
'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt',
'luggage': '12345'}
import sys, pyperclip
if len(sys.argv) < 2:
print('Usage: py pw.py [account] - copy account password')
sys.exit()
account = sys.argv[1] # first command line arg is the account name
if account in PASSWORDS:
pyperclip.copy(PASSWORDS[account])
print('Password for ' + account + ' copied to clipboard.')
else:
print('There is no account named ' + account)
I really don't know what to do. After running win+r and typing e.g. pw email i get only 'usage:py bla bla bla.. nothing else whatever i wrote in win+r
the bat file is like:
'''call C:\Users\Rostek\anaconda3\Scripts\activate.bat
C:\Users\Rostek\anaconda3\python.exe "C:\Users\Rostek\.spyder-py3\Projekty\pw.py"
#pause'''
I cannot pass the arguments I think. I have read all the internet and found nothing like this.
please help. It's program from the book. I am using anaconda3.
You might want to think about what your problem is supposed to do.
if len(sys.argv) < 2:
print('Usage: py pw.py [account] - copy account password')
sys.exit()
This clearly does what it should.
Your question is actually not about python, but about win+r passing arguments.
Why do you want to run your program with win+r in the first place?
After running win+r and typing e.g. pw email...
What you want is to open the command line/ powershell/ bash instead and simply pass the variables to your programm with python3 programname.py email directly.
If you want to do that even cleaner you should use an argparser.
EDIT:
After the clarification in the comments:
The problem is that if you execute a script with win+r you will get the output- for a fraction of a second- then the cmd is closed...
So unless you specify a location in your script to where the pw is written to, you´ll have it in your console. Which blinks and vanishes immediately. Therefore open a console and execute the program from there.
Or you might want to have a look at this:
Output to clipboard

how to provide username and password while checking out the code from SVN using python script without third party module

I am able to write a script to checkout the code from SVN issue using "pysvn" module but just wanted to know is there any way I can do without pysvn also ? Because pysvn is third party library which I have to install separately on linux and windows both which I don't want. Please help me get alternate way in which I don't have to install any third party module code -
import pysvn,os,shutil
def getLogin(realm, username, may_save):
svn_user = '<my-username>'
svn_pass = '<my-password>'
return True, svn_user, svn_pass, False
def ssl_server_trust_prompt( trust_dict ):
return (True # server is trusted
,trust_dict["failures"]
,True) # save the answer so that the callback is not called again
def checkOut(svn_url,dest_dir):
if os.path.isdir(dest_dir):
shutil.rmtree(dest_dir)
os.mkdir(dest_dir)
client = pysvn.Client()
client.callback_ssl_server_trust_prompt = ssl_server_trust_prompt
client.callback_get_login = getLogin
client.checkout(svn_url,dest_dir)
else:
os.mkdir(dest_dir)
client = pysvn.Client()
client.callback_ssl_server_trust_prompt = ssl_server_trust_prompt
client.callback_get_login = getLogin
client.checkout(svn_url,dest_dir)
print "Checking out the code hang on...\n"
checkOut('<svn-repo>','ABC')
print "checked out the code \n"
print "Checking out the code hang on...\n"
checkOut('<svn-repo>','XYZ')
print "checked out the code\n"
print "Checking out the code hang on...\n"
checkOut('<svn-repo>','MNP')
print "checked out the code \n”
You can pass username and password as arguments:
$ svn update --username 'user2' --password 'password'
You can make Executable of ur script which will include the pysvn into binary file, thus wouldn't need to import or pip install any library, n ur code will run on python-less machines too

How to hide the password in fabric when the command is printed out?

Say I have a fabfile.py that looks like this:
def setup():
pwd = getpass('mysql password: ')
run('mysql -umoo -p%s something' % pwd)
The output of this is:
[host] run: mysql -umoo -pTheActualPassword
Is there a way to make the output look like this?
[host] run: mysql -umoo -p*******
Note: This is not a mysql question!
Rather than modifying / overriding Fabric, you could replace stdout (or any iostream) with a filter.
Here's an example of overriding stdout to censor a specific password. It gets the password from Fabric's env.password variable, set by the -I argument. Note that you could do the same thing with a regular expression, so that you wouldn't have to specify the password in the filter.
I should also mention, this isn't the most efficient code in the world, but if you're using fabric you're likely gluing a couple things together and care more about manageability than speed.
#!/usr/bin/python
import sys
import string
from fabric.api import *
from fabric.tasks import *
from fabric.contrib import *
class StreamFilter(object):
def __init__(self, filter, stream):
self.stream = stream
self.filter = filter
def write(self,data):
data = data.replace(self.filter, '[[TOP SECRET]]')
self.stream.write(data)
self.stream.flush()
def flush(self):
self.stream.flush()
#task
def can_you_see_the_password():
sys.stdout = StreamFilter(env.password, sys.stdout)
print 'Hello there'
print 'My password is %s' % env.password
When run:
fab -I can_you_see_the_password
Initial value for env.password:
this will produce:
Hello there
My password is [[TOP SECRET]]
It may be better to put the password in the user's ~/.my.cnf under the [client] section. This way you don't have to put the password in the python file.
[client]
password=TheActualPassword
When you use the Fabric command run, Fabric isn't aware of whether or not the command you are running contains a plain-text password or not. Without modifying/overriding the Fabric source code, I don't think you can get the output that you want where the command being run is shown but the password is replaced with asterisks.
You could, however, change the Fabric output level, either for the entire Fabric script or a portion, so that the command being run is not displayed. While this will hide the password, the downside is that you wouldn't see the command at all.
Take a look at the Fabric documentation on Managing Output.
Write a shell script that invokes the command in question with the appropriate password, but without echoing that password. You can have the shell script lookup the password from a more secure location than from your .py files.
Then have fabric call the shell script instead.
This solves both the problem of having fabric not display the password and making sure you don't have credentials in your source code.
from fabric.api import run, settings
with settings(prompts={'Enter password: ': mysql_password}):
run("mysql -u {} -p -e {}".format(mysql_user,mysql_query))
or if no prompt available:
from fabric.api import run, hide
with hide('output','running','warnings'):
run("mycommand --password {}".format(my_password))

Categories

Resources