How to automate Jenkins ssh credentials creation in python? - python

I am trying to create Jenkins user & ssh_key credentials in python with below script but it's not working anyhow! It gives some server exception with some html data.
I am not sure what things are going wrong here.
from api4jenkins import Jenkins
jenkins_client = Jenkins('http://xx.xx.xx.xx:8080', auth=('admin', 'xxxxxxx'))
with open("/home/oem/.ssh/id_rsa","r") as file:
ssh_key = file.read()
sshPayload = f'''<com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey plugin="ssh-credentials#1.16">
<scope>GLOBAL</scope>
<id>Kubernetes_Master</id>
<description>SSH Credential for K8S Master</description>
<username>ubuntu</username>
<privateKeySource class="com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey\$DirectEntryPrivateKeySource">
<privateKey>{ssh_key}</privateKey>
</privateKeySource>
</com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey>'''
jenkins_client.credentials.create(sshPayload)
I tried to give the key as it is in the section but no luck.Even mentioning the key file located at Jenkins server doesn't work either. Any help on this will be appreciated.
I followed the below mentioned in below question for simple user and password way but for ssh key there are no more discussions.
Question Link

Related

Flask using password of user without providing it in clear text

I have a flask application where I login to another service for which I need login data. So I have my endpoint in the flask application /service and this endpoint uses a username and password which I currently have in clear text, meaning
#app.route('/service'), methods = ['GET','POST'])
def access_service(test: str):
username = 'user1'
password = 'passwordincleartext'
req = 'https://anotherservice.com/'
headers = {'Content-type': 'application/json'}
HTTPAUTH = HTTPBasicAuth(username, password)
my_data = '''{"myjsonfield":''' + test + '''}'''
requests.get(req,headers=headers,data=my_data,auth=HTTPAUTH)
My problem is that I can not provide the username and password with the request because another program is using my flask application and this program is an external one where I can not manipulate the request on /service. Is there a way to use a username and password securely, meaning not in clear text, in flask, without having to create a database?
Your passwords or any login credentials should not be included in your code, for that it's preferable and more secure to use something like dot.env, and you'll keep this based to where you project is and not upload this file any way, not even your github repo. please check the following it's a simple and clear explanation of how you can use dot.env
https://dev.to/emma_donery/python-dotenv-keep-your-secrets-safe-4ocn
I suggest you create 2 files, where one will be local to each machine running the code and one will be pushed to github with your code where it shows only the variable names, and example bellow:
# .env file (local machine specific)
USERNAME=user1
PASSWORD=passwordincleartext
# example.env file (pushed with your code)
USERNAME=<ask-from-maintainer>
PASSWORD=<ask-from-maintainer>
NOTE: example.env file will not be used in your code, but you will need it if you are running the code on a different machine, this way all you need is to copy and paste the file, rename it to .env and replace the variables values with the right credentials. This way when you run your code it will work on the new environment without any issue

Are function/host keys directly available inside an Azure Function written in Python?

When writing an Azure Function in Python, I would expect to be able to access the host and function keys from the environment. Is this possible? All the examples I've seen do it by calling a get request, which seems like a lot of code to access something that I've set through the website.
This question is very similar, but not language specific.
It sounds like you want to get the response of the Host API admin/host/keys of Azure Functions as below, so please refer to Azure Functions wiki page Key management API
Here is my sample code.
# App Credentials, to get it see the figures below
username = "<your username like `$xxxxx`>"
password = "<your password>"
functionapp_name = "<your function app name>"
api_url = f"https://{functionapp_name}.scm.azurewebsites.net/api"
site_url = f"https://{functionapp_name}.azurewebsites.net"
import base64
import requests
auth_info = f"{username}:{password}"
base64_auth = base64.b64encode(str.encode(auth_info)).decode()
print(base64_auth)
jwt_resp = requests.get(f"{api_url}/functions/admin/token", headers={"Authorization": f"Basic {base64_auth}"})
jwt = jwt_resp.text.replace("\"", "", -1)
print(jwt)
keys_resp = requests.get(f"{site_url}/admin/host/keys", headers={"Authorization": f"Bearer {jwt}"})
print(keys_resp.text)
It works and its result as below.
For getting the username and password of App Credentials, please see the figures below.
Fig 1. On Azure portal, open the Platform features tab of your Function App and click the Deployment Center link
Fig 2. Select the FTP option in the first step of SOURCE CONTROL and click the Dashboard button to copy the values of Username and Password, but just use the part of Username with $ prefix as username variable in my script. Ofcouse, you also can use them in tab User Credentials tab.
Also, you can refer to my answer for the similar SO thread Unable to access admin URL of Azure Functions using PowerShell, and my figures below come from that.
Update: For using Azure Function for Python in container, please refer to the figure below to get the deployment credentials.

Authentication OneDrive API Python

Using code sample from GitHub that is specifically for setting up authentication for Python access to OneDrive API (I'm beginning to think this source is outdated), I've failed to make it past the part where you paste code provided by Microsoft after executing program..
Python code:
import onedrivesdk
redirect_uri = 'https://login.microsoftonline.com/common/oauth2/nativeclient'
client_secret = '*this code omitted*'
client_id='*this code omitted*'
api_base_url='https://api.onedrive.com/v1.0/'
scopes=['onedrive.readwrite']
http_provider = onedrivesdk.HttpProvider()
auth_provider = onedrivesdk.AuthProvider(
http_provider=http_provider,
client_id=client_id,
scopes=scopes)
client = onedrivesdk.OneDriveClient(api_base_url, auth_provider, http_provider)
auth_url = client.auth_provider.get_auth_url(redirect_uri)
# Ask for the code
print('Paste this URL into your browser, approve the app\'s access.')
print('Copy everything in the address bar after "code=", and paste it below.')
print(auth_url)
code = raw_input('Paste code here: ')
client.auth_provider.authenticate(code, redirect_uri, client_secret)
After executing code and pasting url in browser, a popup shows up, where I verify that I want to give my app access to API.. I hit "Ok."
I am then presented with code in URL taskbar. I copy and paste code into program..
Then the error I get is:
raise Exception(str(message["error"]))
Exception: invalid_request
Link to GitHub source used: https://github.com/OneDrive/onedrive-sdk-python
Note: I had to omit scopes such as the first two in this list:
scopes=['wl.signin', 'wl.offline_access', 'onedrive.readwrite']
because they apparently don't exist (according to error code provided by Microsoft after pasting URL into taskbar)
Is there a better source for setting up authentication for a Python program to communicate with OneDrive API?
I am a relatively new Python user, your patience is appreciated.
I ran into the same issue and the solution was to include the redirect_uri in the app registration.
This can be done at https://portal.azure.com/ und Azure Active Directory > App registrations > "Your App" > Authentication. In my case, I needed to add http://localhost:8080/ to the redirect URIs.
I found the suggestion here:
https://github.com/OneDrive/onedrive-sdk-python/issues/98
Hope it helps someone save some time.

EMBED-API, Google analytics, server-side authorization

I can't seem to get the EMBED-API Server-side Authorization demo to work:
https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/
In the demo it says the following:
Once the library is installed you can add the following python module
to your project and invoke the get_access_token() method to get an
access token that you can use to authorize the Embed API.
# service-account.py
from oauth2client.service_account import ServiceAccountCredentials
# The scope for the OAuth2 request.
SCOPE = 'https://www.googleapis.com/auth/analytics.readonly'
# The location of the key file with the key data.
KEY_FILEPATH = 'path/to/json-key.json'
# Defines a method to get an access token from the ServiceAccount object.
def get_access_token():
return ServiceAccountCredentials.from_json_keyfile_name(
KEY_FILEPATH, SCOPE).get_access_token().access_token
I've succesfully done all the previous steps, but this one I just can't get my head around. Where do I put this code? It seems as if it should be put in a .py file.
Can someone please help?
It depends on your implementation, but basically you want to run your service account code on your server, and have the access token passed to your client application so it can make authorized requests from the browser.
The whole app is open sourced and you can see where the service account code is in the source code.
As in the demo, if you are using django or app engine it is easy to put python server code in your site which will return the token and replace the value in template code.
Add that code in service-account.py file and upload it on your server using FTP. I saved the code using dreamweaver, updated the path and added following line at the end of the service-account.py file:
print get_access_token()
Upload .JSON file in same directory and ran the command python service-account.py to get access_token.

Google App Engine 1.7.6 Remote API error

Prior to the 1.7.6 dev server update, I was able to use /_ah/remote_api to upload test data to my dev server having to go through the authentication process by not entering a username and password (hitting return twice). Since the update, this now continuously asks for a username and password, regardless of what I put in - often says error incorrect username or password. I am currently targeting localhost:8080,
def auth_func():
return (raw_input('Username:'), getpass.getpass('Password:'))
remote_api_stub.ConfigureRemoteApi(None, '/_ah/remote_api', auth_func,
'localhost:8080')
though there are two new servers including the API server and the admin server. Has anyone else encountered this? if so, how did you fix it?
Thanks!
Jon
Apparently thanks to Tim - If you use the new dev_appserver then you need to sepecify a email like looking username and a single character as a password on the local development server in order for it to accept and move past the login stage.

Categories

Resources