I am pretty new to Splunk and Python.
I am using Splunklib.client to connect the Splunk API. My code is below:
import splunklib.client as client
import splunklib.results as result
HOST = 'Localhost'
PORT = '8000
USERNAME = "username"
PASSWORD = "password"
service = client.connect(
host=HOST,
port=PORT,
username=USERNAME,
password=PASSWORD)
rr = results.ResultsReader(service.jobs.export("query")
My questions is I have multiple host such as localhost1, localhost2,localhost3 etc, is there a way to get the data through this module on multiple host?
Thanks
Should be as simple as:
service1 = client.connect(
host=HOST1,
port=PORT1,
username=USERNAME1,
password=PASSWORD1)
rr = results.ResultsReader(service1.jobs.export("query")
service2 = client.connect(
host=HOST2,
port=PORT2,
username=USERNAME2,
password=PASSWORD2)
rr = results.ResultsReader(service2.jobs.export("query")
Related
Is it Possible if the Connection to a Server cuts off for some reason that I get a Text or something, so I know that the Error has something to do with the Server?
import paramiko
import time
def connSFTP(ssh_key_filepath,host,user):
#Fehleroptionen 1. Pfad zum SSH-KeyError
#-SSH-Key vorhanden?
#2.Host und/oder Username ist falsch
k = paramiko.RSAKey.from_private_key_file(ssh_key_filepath) #SSH KEY
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect( hostname = host, username = user , pkey = k )
sftp = c.open_sftp()
return sftp
def main():
ssh_key_filepath = '/home/dtv/.ssh/id_rsa'
hostname = 'HostAdress'
username = 'user'
sftp = connSFTP(ssh_key_filepath,hostname,username)
print('Connected')
time.sleep(30)
#sftp.close()
if __name__ == '__main__':
main()
I built in a sleep, so I can kill the procedure for the Connection and Simulate the Connection lost in time.
You should use exception handling with the following:
Raises:
BadHostKeyException – if the server’s host key could not be verified
Raises:
AuthenticationException – if authentication failed
Raises:
SSHException – if there was any other error connecting or establishing an SSH session
Raises:
socket.error – if a socket error occurred while connecting
Paramiko api documentation link: http://docs.paramiko.org/en/1.15/api/client.html#paramiko.client.SSHClient.connect
I am using Python 3.6.6 and i need to establish a SSH connection to a server.
I have the IP and port for the server, and i use my credentials to login, usually through putty. The servers is on Linux/Suse .
I need to get the list of directories in the server folder, and copy the content of one of the files out. I am using paramiko, and i need the connection to be open so i can execute and interact with the server.
I am not sure i am clear enough.
Below is my code
import paramiko
nbytes = 4096
hostname = '123.123.123.123'
port = 22020
username = 'uname'
password = 'pwd'
command = 'vi log'
client = paramiko.Transport((hostname, port))
client.connect(username=username, password=password)
stdout_data = []
stderr_data = []
session = client.open_channel(kind='session')
session.exec_command(command)
while True:
if session.recv_ready():
stdout_data.append(session.recv(nbytes))
if session.recv_stderr_ready():
stderr_data.append(session.recv_stderr(nbytes))
if session.exit_status_ready():
break
print ("rec status: ", session.recv_ready())
print ("exit status: ", session.recv_exit_status())
print ("".join(stdout_data))
print ("".join(stderr_data))
session.close()
client.close()
I want to connect to my remote machine with python module paramsiko. First, I try with password, it is ok, like this:
import paramiko
import socket
import os
paramiko.util.log_to_file('demo_sftp.log')
username = 'xxxxx'
hostname = 'dev81'
Port = 22
password = "xxxxx"
t = paramiko.Transport((hostname, Port))
t.connect(None, username, password)
sftp = paramiko.SFTPClient.from_transport(t)
# dirlist on remote host
dirlist = sftp.listdir('.')
print("Dirlist: %s" % dirlist)
then I want to remove password, use key, according to demo in demo_sftp like this:
import paramiko
import socket
import os
paramiko.util.log_to_file('demo_sftp.log')
username = 'xxxxx'
hostname = 'dev81'
Port = 22
password = None
host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
hostkeytype = host_keys[hostname].keys()[0]
hostkey = host_keys[hostname][hostkeytype]
print('Using host key of type %s' % hostkeytype)
t = paramiko.Transport((hostname, Port))
t.connect(hostkey, username, password, gss_host=socket.getfqdn(hostname),
gss_auth=True, gss_kex=True)
sftp = paramiko.SFTPClient.from_transport(t)
# dirlist on remote host
dirlist = sftp.listdir('.')
print("Dirlist: %s" % dirlist)
This fail with Exception paramiko.ssh_exception.BadAuthenticationType: ('Bad authentication type', [u'publickey', u'password']) (allowed_types=[u'publickey', u'password'])
And I can login with command ssh xxxxx#dev81 without password
If you Have passphrase for the Key pair
It throws this error
paramiko.ssh_exception.BadAuthenticationType: ('Bad authentication type', [u'publickey', u'password']) (allowed_types=[u'publickey', u'password'])
To Resolve this
ssh.connect('<your ip>', port=22, username='<username>',password='<passphrase for the RSA key>', key_filename='<full path of the private key>')
I can do ssh from one server to another using this:
# ssh root#1.2.4.148
The following code is doing the same in pythonic way:
import paraminko
#paramiko.util.log_to_file('ssh.log') # sets up logging
client = paramiko.SSHClient()
client.load_system_host_keys()
client.connect('1.2.4.148')
stdin, stdout, stderr = client.exec_command('ls -l')
But if I need to connect to third server from the second server, I can do this:
# ssh -t root#1.2.4.148 ssh root#1.2.4.149
How is this done in python?
My current server (250) has password less keys saved with 148 server for easy access. But connection to 149 from 148 will need password if that matters.
This python function will connect to middle_server first and then to last_server. It will execute the command "mycommand" on last_server and return it's output.
def myconnect():
middle_server='1.2.3.4'
middle_port=3232
middle_user='shantanu'
middle_key_filename='/root/.ssh/id_rsa.pub'
last_server='6.7.8.9'
last_port=1224
last_user='root'
last_password='xxxxx'
mycommand='pwd'
import paramiko
proxy_client = paramiko.SSHClient()
proxy_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
proxy_client.connect(middle_server, port=middle_port, username=middle_user, key_filename=middle_key_filename)
transport = proxy_client.get_transport()
dest_addr = (last_server, last_port)
local_addr = ('127.0.0.1', 1234)
channel = transport.open_channel("direct-tcpip", dest_addr, local_addr)
remote_client = paramiko.SSHClient()
remote_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
remote_client.connect('localhost', port=last_port, username=last_user, password=last_password, sock=channel)
(sshin1, sshout1, ssherr1) = remote_client.exec_command(mycommand)
print sshout1.read()
except:
print "error"
return 0
I'm trying to use Twisted's ProxyAgent class to connect to a proxy server and make HTTP requests, however the server requires a username and password. Is it possible to specify these credentials to the server using ProxyAgent?
endpoint = TCP4ClientEndpoint(reactor, host, port)
agent = ProxyAgent(endpoint)
# Maybe need to pass auth credentials in the header here?
body = agent.request("GET", path)
Figured out the problem, the Proxy-Authorization field has to be set in the headers:
endpoint = TCP4ClientEndpoint(reactor, host, port)
agent = ProxyAgent(endpoint)
headers = {}
auth = base64.b64encode("%s:%s" % (username, password))
headers["Proxy-Authorization"] = ["Basic " + auth.strip()]
body = agent.request("GET", path, Headers(headers))