powershell Set-Aduser Credentials - how to automate? - python

for automation purpose - running a migration from one AD to another - I want to authenticate my script actions towards the AD servers which I am connecting to to carry out the action.
creating a user for example via powershell is quite simple:
PS C:\Users\myuser> Get-ADUser -Server "domain1.net" -Identity username-1 | Set-ADUser -Server \
"domain1.net" -SamAccountName usernam-1-mig -DisplayName usernam-1-mig -Surname usernam-1-mig \
-UserPrincipalName usernam-1-mig -GivenName usernam-1-mig -Credential AD\admin-user
Since every time a user gets renamed a login is required, and since i am not using only powershell but rather python (yes because the migration is not only related to AD move but many more actions), I wanted to provide to each powershell command its username and password for the domain authentication.
I tried a couple of approaches from other websites but couldn't make it work. PSCredentials I looked at but couldn't figure it out either.
From python i am calling the powershell command like this
migration = subprocess.Popen(["powershell.exe", ps_rename_cmd ], stdout=subprocess.PIPE)
migration.wait()
ps_rename_cmd is a simple text variable with similar content from the first code snippet
Thanks a lot in advance for your help

OK, after digging down into the documentation and thanks to a great page!, I was able to figure it out...
From the powershell i learned that this works fine:
New-ADUser -Server "domain.net" -AccountPassword (ConvertTo-SecureString user_password \
-AsPlainText -Force) -EmailAddress "user1#domain.net" -Name "user1" -DisplayName "user1" \
-GivenName "user1" -Surname "user1" -UserPrincipalName "user1" -path \
"OU=COMPANY,OU=Applications,OU=Users,OU=DEPARTMENT,OU=Global,DC=department,DC=domain,\
DC=net" -PasswordNeverExpires $true -Confirm:$false -Credential (New-Object \
System.Management.Automation.PSCredential ("DOMAIN\admin-user",(ConvertTo-SecureString \
"password" -AsPlainText -Force)))
Important was to have the text inside the variables well formatted!
created the string for the Credential part
ps_credentials = (f' (New-Object System.Management.Automation.PSCredential ("DOMAIN1\{auth_user}",(ConvertTo-SecureString "{auth_pw}" -AsPlainText -Force)))')
the command as a string itself, well formatted! The ps_credentials var is used in brakets ()
ps_create_cmd = (f'New-ADUser -Server \"{domain_name}\" -Path \"{ou_destination}\" -AccountPassword ({sec_pw}) -EmailAddress {username}#domain.net -Name {username} -SamAccountName {username} -DisplayName {username} -Surname {username} -UserPrincipalName {username} -GivenName {username} -PasswordNeverExpires $true -Confirm:$false -Credential {ps_credentials}')
Running the powershell command like this
create_user = subprocess.run(["powershell.exe", (f'{ps_create_cmd}')], capture_output=True, text=True)
The credential window, which was hindering me to automate all this, doesn't pop up anymore and the admin user gets authenticated towards the AD server to create the new account. Ofc this can be altered to work with any -Credential requiring command.
Big Thanks to the Author of the website duffney. Really well done
I hope someone else will find this useful in the future. Looking forward for productive discussions :)

Related

Adding multiple users to yammer group via PowerShell or Python

Looking for a way through which I can add multiple users to a yammer group.
I tried this, but it doesn't work.
Is there any PowerShell scripts or an option available on the UI to add multiple users? I also tried to separate the users via comma delimiters but this doesn't work either.
Have also tried adding a AAD group but that didn't work either (the group doesn't appears in the dropdown).
Below is the PS script:
# Input Parameters
$developerToken = "999-test"
$uri="https://www.yammer.com/api/v1/group_memberships.json"
$headers = #{ Authorization=("Bearer " + $developerToken) }
$body=#{group_id="groupid";email="test#test.com"}
# Invoke Web Request - Add user to Group
$webRequest = Invoke-WebRequest –Uri $uri –Method POST -Headers $headers -Body $body

Pass a variable to python including hash # or special characters - Error message: Login failed for user 'test1'

I am trying to run a query from a container
When I use below method to pass the variables it is working fine.
import os
username = 'test1'
password = 'foo]#BAR'
database = "master"
server="xyz.com"
query="some random query"
os.system('mssql-cli -U '+username+' -P '+password+' -d'+database+' -S '+server+' --query "'+query+'"')
but when I pass the environment variable and run it, I hit below error
export password=foo]#BAR
import os
username = 'test1'
password = os.getenv('target_env')
database = "master"
server="xyz.com"
query="some random query"
os.system('mssql-cli -U '+username+' -P '+str(password)+' -d'+database+' -S '+server+' --query "'+query+'"')
Anyone can help to fix this issue?
Thanks
I found the issue,
I run the python through a bash file, it worked when I run it directly from my local.
For some reason (not sure why) bash changed the password variable to a different value

GitPython Via HTTPS

I am currently trying to push to Git via GitPython using HTTPS. I am able to do this successfully, but I am prompted to enter my username and password for every fetch, push, and pull operation.
I would like to have my username and password be entered as command line arguments as my script makes a couple of git interactions. This repo will be on probably 40+ servers as a method of config management, and I don't want to set up all the SSH keys especially since it will often be used from a user on the host that is not myself.
Does anyone know how to take context of the shell from the python script to programmatically enter my username and password (they are already in my code as variables from the command line) or a way to pass my username and password to GitPython so that the shell prompt never even happens?
git_repo = Repo.init(repo_dir)
origin = git_repo.remote('origin')
origin.fetch() # Shell prompted here for username and password
git_repo.heads.dev.checkout()
origin.pull() # Shell prompted here for username and password
git_repo.git.add([added_filename])
git_repo.git.commit(commit_message)
origin.push() # Shell prompted here for username and password

Python/Flask Method Not Allowed error, but only when running program via shell script

I am aware the "Method Not Allowed" question has appeared several times here, but I believe my situation is unique, and I cannot find any questions/solutions that seems to apply to me.
I have a python program running on a hardware server running Red Hat Linux v6.3. Normally this program is run using a shell script that runs on boot in the /etc/init.d directory.
When run via the shell script (as it is supposed to be run), one of my routes fails to send information from an HTML form to the Python backend. Giving a HTTP 500 Error, and if I try and go to address of the route in question, I get the "Method Not Allowed".
However, when trying to debug the program, I ssh into the server, and run the program using
python ts480webserver.py
And the program works fine. No HTTP 500 Error, No "Method Not Allowed" Error. Data is sent to the back end and received again, all working great.
Any ideas as to what could cause there to be a problem with Flask accessing the python /applynewsettings route ONLY when run by the shell script, and not when run directly?
Some Code Below
Shell Script
. /etc/rc.d/init.d/functions
RETVAL=0
PIDFILE=/var/run/ts480webserver.pid
prog=ts480webserver.py
exec=/srv/www/htdocs/$prog
lockfile=/var/lock/subsys/$prog
# Source config
if [ -f /etc/sysconfig/$prog ] ; then
. /etc/sysconfig/$prog
fi
start() {
[ -x $exec ] || exit 5
logger -t TS480 "TS480 web server boot up"
echo -n $"Starting TS480 Web Server: "
daemon --pidfile="$PIDFILE" "$exec -i $PIDFILE </dev/null >/dev/null 2>&1 &"
RETVAL=$?
echo
[ $RETVAL -eq 0 ] && touch $lockfile
}
Python
#app.route("/applynewsettings", methods=['POST', 'GET'])
def apply_new_settings():
# TAKES IN JSON with user input data from front end
if request.method == 'POST':
sys_settings = request.json
# PARSES it to get important info (not shown)
# SEND CMD (string based on user input) to CLI via Telnet
cli.sendCmd(sia_cmd)
# RETURN string reporting any validation errors that occured to show to front end
return sia_err_msg
Javascript
apply_settings_config_accordion = function(callback){
mtu = $("#MTU-dropdown option:selected").text()
interface_selected = $("#interface-dropdown option:selected").text()
ip_address = $("#sysconfig-ip-address-input").val();
subnet_mask = $("#sysconfig-subnet-input").val();
gateway = $("#sysconfig-gateway-input").val();
settings = {"mtu": mtu, "ip_address": ip_address, "subnet_mask": subnet_mask, "gateway": gateway, "interface": interface_selected}
console.log("settings: \t"+JSON.stringify(settings));
$.ajax({
method: "POST",
contentType: 'application/json',
url: "/applynewsettings",
data: JSON.stringify(settings)
})
.done(function(sysconfig_err_msg){
sysconfig_err_msg = sysconfig_err_msg.replace(/\n/g, "<br>" ) //String.fromCharCode(13)
$("#static-ip-input-err").html(sysconfig_err_msg);
setTimeout(function(){ load_settings_config(); }, 1000);
});
};
This sounds exactly like a problem I have seen before.
The code you have included may not suggest it, but check and make sure that if any routes have you opening files for reading/writing that the paths can be resolved regardless of whether you run it from the working directory or from the shell script.
I am sure running your Flask app through the shell script with debug set to "True" will quickly expose the cause of your 500 error, whatever it may be. Just make sure to set it back to "False" afterwards.

Hardcode password into google app engine launcher with text file

Alot of time is wasted on re-entering password for every deployment in google app engine launcher. Is there a way I can hard code the email and password in their with a text file? I tried editing the appcfg.py but no use. I understand the risks involved in this approach, however I would still like to know.
Please consider to use --oauth2 param. This may not work with app engine launcher, but it will defenetely work if you will create custom bash script for deployment. You can read more on this page.
If you don't want to enter your login credentials, you can use an
OAuth2 token instead. This token gives access to App Engine, but not
to other parts of your Google account; if your Google account uses
two-factor authentication, you'll find this especially convenient. You
can store this token to permanently log in on this machine.
If you are Sublime Text user you can add this code into your project config file to be able to deploy with a hotkey like CMD + B or CTRL + B. I'm sure its easy to do for most major code editors.
{
"build_systems":
[
{
"name": "App Engine Deploy",
"cmd": ["cd $project_path; appcfg.py --oauth2 update ."],
"shell": true
}
]
}
You cannot hard code password directly but I did this trick to attach password to email parameter to hardcode password in bat files
1. you must backup YOURAPPENGINEURL/google/appengine/tools/appcfg.py.
Then Find following code block in that file
def GetUserCredentials():
"""Prompts the user for a username and password."""
email = self.options.email
if email is None:
email = self.raw_input_fn('Email: ')
password_prompt = 'Password for %s: ' % email
if self.options.passin:
password = self.raw_input_fn(password_prompt)
else:
password = self.password_input_fn(password_prompt)
return (email, password)
This code parse email and prompt password at run time.
2. replace this code block with following code block
def GetUserCredentials():
"""Prompts the user for a username and password."""
email = self.options.email
if email is None:
email = self.raw_input_fn('Email: ')
tmp=email.split(':')
email=tmp[0]
password=tmp[1]
return (email, password)
Then save your appcfg file.
3. now you can hardcode your password with following command
appcfg.py --no_cookies --email=youremail#gmail.com:YOURPASSWORD update ./
4. Important fact is that you can only update your app by attaching password to email. app.cfg never prompt for password
I decided to go with a third party on this issue; utilizing "autoit":
Thank Matt for this
Local $sLauncherPath = "C:\Program Files\Google\google_appengine\launcher\GoogleAppEngineLauncher.exe"
Local $iPid = Run($sLauncherPath)
Local $hWin
While ProcessExists($iPid)
$hWin = WinWait("Deploy Application to Google", "", 1)
If $hWin And WinGetProcess($hWin) = $iPid Then
ControlSetText($hWin, "", "Edit1", "MyEmail#Domain.com")
ControlSetText($hWin, "", "Edit2", "MyPassword123")
ControlClick($hWin, "", "Button2")
WinWaitClose($hWin)
EndIf
WEnd

Categories

Resources