How do I print multiple variables in a line of code? - python

!/usr/bin/env python3
import random
import socket
import time
import sys
import os
print ('Ping Of Death')
os.system("clear")
print
ip_death = input("ip:")
packetsize = input("size:")
print (ip_death)
os.system("ping ip_death, -s packetsize ")
and the output I get is
ping: ip_death,: Name or service not known
I know the variables are defined because of print (ip_death) that I have tested and always comes out with my input.
I'm new to python and just wondering how I can run both of these variables in the in one command. If wonder I'm trying to run Ping example.com -s "size of packet".

You need to format the string:
os.system("ping {}, -s {}".format(ip_death, packet_size))
You can also verify you're doing the right thing by printing the command before executing it:
command = "ping {}, -s {}".format(ip_death, packet_size)
print(command) # see that its what you wanted to execute
os.system(command)
Currently you just baked the names into the strings. Python doesn't automagically know what it should format and what it shouldn't.
Also - black hat hacking is bad <3

os.system(f"ping {ip_death}, -s {packetsize} ")
You can use f-strings to insert a variable directly into a string. f-strings are defined by f"{variable}"
Note:
os.system(f"ping {ip_death}, -s {packetsize} ")
Will still fail, the comma will throw an error in cmd,
Ping request could not find host 192.168.0.1,. Please check the name and try again.
You need to remove the comma for it to work;
os.system(f"ping {ip_death} -s {packetsize} ")
ping 192.168.0.1 -s 1
Pinging 192.168.0.1 with 32 bytes of data:
Reply from 192.168.0.1: bytes=32 time<1ms TTL=255
Timestamp: 192.168.0.1 : 4742664

Related

UTF-8 byte order mark appears when using os.system() but not when printing

I have an issue where when I print a command that I want the python script to run, it prints in perfect syntax, however, when I try to use that exact same variable in order to run the command using os.system() it won't run and gives me an error. See Below:
wholecommand = '''python3 mysshpass.py --password "%s" ssh %s "%s" ''' % (password, sshprefix, runcommand)
print(wholecommand)
response = os.system(wholecommand)
So in this instance I've defined the command I want to run based off of some random variables but when I run this code it returns with the following:
python3 mysshpass.py --password "***" ssh root#10.245.10.72 "echo -e '***
***' | passwd"
ssh: Could not resolve hostname \357\273\27710.245.10.72: Name or service not known
The issue here is that for whatever reason my script is inserting \357\273\277 into the thread where the ip address goes and I just can't figure out why.

how to pass variable to cmd that used by subprocess.call

we are using python3 on our Linux machines
I am trying to pass the variable IP , in cmd
#!/usr/bin/python3
import sys, os, logging
import subprocess
IP = '127.0.0.1'
COMMAND = "ping -c 3 IP"
subprocess.call(COMMAND, shell=True)
subprocess.Popen(COMMAND,stdin=subprocess.PIPE,stdout=subprocess.PIPE, shell=True).stdout.read()
since we get the error about ping: unknown host IP
I am thinking how to pass the IP variable , so later I can execute the cmd with subprocess.call and subprocess.Popen
Instead of providing COMMAND as a string, it's safer to provide it as a list instead and leave shell at its default value of False. That way, you don't have to perform shell escaping in case any arguments contain "special" characters like spaces:
COMMAND = ["ping", "-c", "3"]
subprocess.call(COMMAND + [IP])
You need to insert the contents of IP into COMMAND. Here, you can simply add the strings like this:
COMMAND = "ping -c 3 " + IP

Ping Command for python

Hello I am making a discord bot with Python but I am not getting to how to add ping in bot...like how much ping does Bor have .I have searched on ggl but it is now working if you know please let me know
For python3 use module ping3: (pip install ping3, needs root privileges).
from ping3 import ping, verbose_ping
ping('google.com') # Returns delay in seconds. 0.0010232925415039062
If your running environment is not windows, you can do this.
You just have to call a system command and check the return code.
If you want to improve this example, you can test the current OS and run the apropriate command.
import os
hostname = "yoururl.com"
response = os.system("ping -c 1 " + hostname)
if response == 0:
print hostname, 'Up'
else:
print hostname, 'Unreachable'

how to check if ssh command ran through pexpect spawn command ran successfully or not .

I am writing a simple python script to test connectivity to multiple linux hosts running centos on them. For this I am thinking of using pexpect module and ssh . pexpect will send the password stored in a variable when prompted for. The problem is that how to check if the password was accepted successfully or not. Is there a way to do so. The code is given below. Please add you expert comments.
This example has code written to ssh to localhost only.So a for loop is not yet included.
import pexpect
from getpass import getpass
import sys
# Defining Global Variables
log_file = '/tmp/AccessValidation'
# Getting password from user and storing in a variable
passs = getpass("Please enter your password: ")
# Connect to server using ssh connection and run a command to verify access.
child = pexpect.spawn("ssh -q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no 127.0.0.1 'uptime'")
child.expect('Password:')
child.sendline(passs)
One of the things you could do is to have an expect for the command prompt. So if your prompt is: someuser#host$ you could do child.expect(".*\$").
Another thing you could do is to have multiple expects and then check those against the ones you want. For example:
i = child.expect([".*\$", "Password Incorrect"])
if i != 0:
print "Incorrect credentials"
else:
print "Command executed correctly"
You can view some examples within Pexpect's readthedocs page. Pexpect also has the pxssh class that is specialized to handle ssh connections and may be of some use also. I personally haven't used it but the syntax seems the same, just with more options relating to ssh.
Thanks Cory Shay for helping me figure out the correct way to solve my problem . Below is the code I have written and this works.
import pexpect
from getpass import getpass
import sys
# Defining Global Variables
log_file = '/tmp/AccessValidation'
# Getting password from user and storing in a variable
passs = getpass("Please enter your password: ")
# Connect to server using ssh connection and run a command to verify access.
child = pexpect.spawn("ssh -q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no 127.0.0.1 'hostname' ")
child.expect('Password:')
child.sendline(passs)
result = child.expect(['Password:', pexpect.EOF])
if result == 0:
print "Access Denied"
elif result == 1:
print "Access Granted"

Automatically generate list of tor exit nodes

I want to automatically generate a list of tor exit nodes that can reach a certain IP address. I scoured the internetfor a while and came across this piece of code from http://sjoerd-hemminga.com/blog/2012/10/block-tor-exit-nodes-using-iptables/
if [[ -z "$1" ]]; then
echo Usage: $0 "<your host's ip>"
exit 1
fi
hostip=$1
for i in $(wget https://check.torproject.org/cgi-bin/TorBulkExitList.py\?ip=$hostip -O- -q |\
grep -E '^[[:digit:]]+(\.[[:digit:]]+){3}$'); do
sudo iptables -A INPUT -s "$i" -j DROP
done
Can someone please help me understand this code better, because every time I try to run it, it produces errors.
Any alternate answers are welcomed but I would like if they are in Python.
import os
import re
import sys
import urllib
if len(sys.argv) != 2:
print "Usage {} <your host's ip>".format(sys.argv[0])
sys.exit(1)
hostip = sys.argv[1]
u = urllib.urlopen('https://check.torproject.org/cgi-bin/TorBulkExitList.py?ip=' + hostip)
for ip in u:
ip = ip.strip()
if re.match('\d+(\.\d+){3}$', ip):
#print ip
os.system('sudo iptables -A INPUT -s "{}" -j DROP'.format(ip))
u.close()
If you have configured Tor to have a control port and server descriptors...
ControlPort 9051
CookieAuthentication 1
UseMicrodescriptors 0
... then you can easily enumerate the exits using stem...
from stem.control import Controller
with Controller.from_port(port = 9051) as controller:
controller.authenticate()
for desc in controller.get_server_descriptors():
if desc.exit_policy.is_exiting_allowed():
print desc.address
That said, if your real question is 'how do I do something using every Tor exit' then please don't! Repeatedly making circuits is harmful to the Tor network, for more about about this see stem's FAQ.
Here(https://github.com/RD17/DeTor) is a simple REST API to determine whether a request was made from TOR network or not.
The request is:
curl -X GET http://detor.ambar.cloud/.
The response is
{
"sourceIp": "104.200.20.46",
"destIp": "89.207.89.82",
"destPort": "8080",
"found": true
}

Categories

Resources