Execute commands to output window using powershell - powershell

I am creating a powershell script to change the sybase database account password. I am using isql.exe to change the password. Below are the steps I am trying to automate:
1) isql.exe -SServerName -UUserAccount -PPassword [Run this command and it should log you in with user account]
2) At this point it is waiting for you to run this command "sp_password 'oldPassword', 'newPassword'" [keyboard Enter]
3) GO [Keyboard Enter]
With the below script I built I am able to login, but unable to execute steps 2 and 3. I see that the screen is waiting for the input Step 2 and Step 3, but how should I write to it?
I am new to powershell, but I tried using Write-Output, Write-Host, Invoke-Expression, Invoke-Command for Step 2 and it did not work
$exe=$args[0] #argument which contains the path to isql.exe
$server=$args[1] #argument which contains server name
$user=$args[2] #argument which contains user account
$oldPassword=$args[3] #argument which contains current password
$newPassword=$args[4] #argument which contains new password
$severPrefix= '-S'
$userPrefix= '-U'
$passwordPrefix='-P'
$scriptPrefix='-E'
$spPasswordCmd= 'sp_password'+' '+ $oldPassword +','+ $newPassword
$serverArg = $severPrefix + $server
$userArg= $userPrefix + $user
$passwordArg= $passwordPrefix + $oldPassword
#Step 1- isql.exe -SserverName -UuserAcount -PoldPassword
&$exe $serverArg $userArg $passwordArg
#Step 2 - After login, execute "sp_password 'oldPassword', 'newPassword'"
#&$spPasswordCmd
#Step 3- Go
Read-Host -Prompt "Press Enter to continue"

What went wrong:
By entering the first command you entered "inside" ISQL prompt.
The powershell script won't send ISQL specific commands (Steps 2 & 3) to that session.
It seems to me that you have two options:
1.
You need to open an ISQL session and send a block of commands to that session.
This is a link about connections on Sysbase but I cannot test the things in there.
2.
By reading the ISQL docs, it seems that you can pass a file with commands to the steps 1:
Read in an operating system file containing a query for execution by
isql: isql -U alma -Ppassword < input_file The file must include a
command terminator. The results appear on your terminal. Read in an
operating system file containing a query and direct the results to
another file: isql -U alma -Ppassword < input_file > output_file
I would spend my time here first. See that in there you can find a link with instructions on how to write the sysbase commands file.

After trying lot of combination, finally I was able to get it to work. Posting my script so that it could be helpful for others.
$exe=$args[0] #argument which contains the path to isql.exe
$server=$args[1] #argument which contains server name
$user=$args[2] #argument which contains user account
$currentPassword=$args[3] #argument which contains current password
$newPassword=$args[4] #argument which contains new password
$outputFilePath=$args[5] #argument which containes spPassword file script path
$spPasswordCmd = "sp_password `'$currentPassword`',`'$newPassword`'"
# Create file:
$spPasswordCmd | Set-Content "$outputFilePath"
# Append to file:
"GO" | Add-Content "$outputFilePath"
isql -S"$server" -U"$user" -P"$currentPassword" -i"$outputFilePath"
write-host "**** Password Change Complete *****"
Read-Host -Prompt "Press Enter to exit.!"

After you login to Sybase using isql.exe, you would need to get into the session of isql.exe to change the password by calling sp_password. In your code, you're are simply executing the login command. I dont think you're getting into the session of isql.exe
Take a look at the below link, I guess it might be useful and probably better way to change the database account password.
https://www.cdata.com/drivers/sybase/powershell/

Related

Postgresql Auto backup using powershell and task scheduler

I am running attached script to backup postgresql database by using task scheduler. Script is executed successfully but backup is not happening. Same script i have run on powershell and it's working fine.enter image description here
I want to schedule daily backup on windows server. Please help me or suggest any alternative to automate the backup.
Regards
Sadam
Try this script, it will create a backup file with a name consisting of a timestamp:
First, create a backup.bat file and just run it (set your credentials and database name):
echo off
echo 'Generate backup file name'
set CUR_YYYY=%date:~10,4%
set CUR_MM=%date:~4,2%
set CUR_DD=%date:~7,2%
set CUR_HH=%time:~0,2%
if %CUR_HH% lss 10 (set CUR_HH=0%time:~1,1%)
set CUR_NN=%time:~3,2%
set CUR_SS=%time:~6,2%
set BACKUP_FILE=%CUR_YYYY%-%CUR_MM%-%CUR_DD%_%CUR_HH%-%CUR_NN%-%CUR_SS%.custom.backup
echo 'Backup path: %BACKUP_FILE%'
echo 'Creating a backup ...'
set PGPASSWORD=strongpas
pg_dump.exe --username="postgres" -d AdventureWorks --format=custom -f "%BACKUP_FILE%"
echo 'Backup successfully created: %BACKUP_FILE%'
As a result, you should see such a picture, and a file with the extension .custom.backup should appear in the directory
If you get an error that the executable file "pg_dump.exe" was not found, then specify the full path to this file, something like "C:\Program Files\PostgreSQL\12\bin\pg_dump.exe", or add a directory with binaries PostgreSQL to environment variables (more details here)
-
To schedule regular execution, you can use the windows task scheduler
Press win + r and enter taskschd.msc
Select Create Basic Task
Then follow the steps of the wizard, specify the schedule, and in the "Action" section, specify "Start a program" and then the path to the backup.bat file
To check that everything is correct, find the task in the list and select Run
You can read more about Postgresql backups on Windows here

openconnect password and cookie input

After 2-3 day search and work now i hope you can help ...
I want to use from openconnect in my program and for auth have 2 solution
1 - use from user and pass (but pass dont have any option for command line and only with standard input can input pass)
2 - used from cookie (but openconnect not work with cookie for me !)
For Cookie i do this
-send user with post method to server
-server ask for password
-send password with post method to server
-if all is ok and auth id = success
-read header and get cookie
open command line and send ip and cookie to openconenct
and Error !
Creating SSL connection failed
command line code
openconnect.exe vpn.server.ip --no-cert-check -C "webvpn=BPlUDg9oaTN2uQQ0DQvH7QopD3x5NahiCHQgTqKQ7KPJg38dSuvqLmYIo9Jskig; Secure,webvpnc=; expires=Thu, 01 Jan 1970 22:00:00 GMT; path=/; Secure,webvpnc=bu:/&p:t&iu:1/&sh:7350D46A8EE85D06&lu:/+CSCOT+/translation-table?textdomain%3DAnyConnect%26type%3Dmanifest&fu:profiles%2F/etc/ocserv/profile.xml&fh:6B5181182D2B5483FBB8D2AA1BCBACC9A70E2BA3; path=/; Secure"
for send user and pass with post method i use from C#
2 - for user and pass i do this work
use from command line for auto fill input with this code
type password | openconnect.exe vpn.server.ip -u username --no-cert-check
and
password | openconnect.exe vpn.server.ip -u username --no-cert-check
and
openconnect.exe vpn.server.ip -u username --no-cert-check < pas.txt
and again error !!!
Password: ReadConsole() failed: The handle is invalid.
now i want to know whats wrong in my code ??
or have any better solution for accept cookie or auto fill input ?
if you have any idea please tell me.
thanks and kind regards.
openconnect command line info
Openconnect Autofill Username and Password
There is a trade-off between convenience and security. Autofill user and password is not recommended in terms of security.
In case you need the convenience to make an autoconnection using openconnect here is a simple example steps:
Simple Steps Example
Create a plaintext password file
mypass.txt
contains only the password:
mysupersecretpassword
Create a script to call openconnect
myscript.sh contains two lines of command:
openconnect --protocol=gp vpn.mycompany.com --user=abc123 --passwd-on-stdin < mypass.txt
./myscript.sh
the second line ./myscript.sh is intentionally added to make the script loop forever thus create a persistent VPN connection.
Make script executable
In terminal line:
chmod +x myscript.sh
Run your script
run your script with a sudo privilege
sudo ./myscript.sh
to exit the loop just press CTRL + C
For More Security
For added security you can make the process not so simple:
put your script and password file in a protected/hidden directory that only root level user can access;
Encrypt the plaintext password file and make another script to decrypt and read the password for example using linux gpg, but you will still have to enter the encryption/decryption passphrase.
In ubuntu you can use this:
openconnect --script ./vpnc.sh target-domain --no-cert-check -u username --passwd-on-stdin < pass.txt
Hope this helps.

Gathering Files from multiple computers into one

I am trying to gather files/folders from multiple computers in my network into one centralized folder in the command console (this is the name of the pseudo server for this set of computers)
Basically, what i need is to collect a certain file from all the computers connected to my network and back it up in the console.
Example:
* data.txt // this is the file that i need to back up and its located in all the computers in the same location
* \console\users\administrator\desktop\backup\%computername% // i need each computer to create a folder with its computer name into the command console's desktop so i can keep track of which files belongs to which computer
I was trying to use psexec to do this using the following code:
psexec #cart.txt -u administrator -p <password> cmd /c (^net use \\console /USER:administrator <password> ^& mkdir \\console\users\Administrator\Desktop\backup\%computername% ^& copy c:\data.txt \\console\USERS\Administrator\DESKTOP\backup\%computername%\)
any other suggestions since im having trouble with this command
Just use the command copy must easy.
take a look:
for /F %%a in (computerslist.txt) do (
copy \\%%a\c$\users\administrator\desktop\%%a\*.txt c:\mycollecteddata\%%a
)
that will copy all files *.txt for all computers that are on computereslist.txt; the copy will be with the current credentials. Save the code on a file *.cmd and execute with the right user, you can create a scheduled taks to start with a user thant is commom for all computers.
Good work.

How to get rid off Password expiry error message when connecting to Oracle/DB2 Database in solaris shell script/perl program?

I am connecting to Oracle/DB2 databases through shell script/ Perl program. Databases that i am connecting will need password change every 60 days. This is according to our security policy and cannot be changed. But this is creating problem when connecting to Databases through shell script or perl program. To connect to oracle DB we use below through shell script:
sqlplus -s ${USER_NAME}/${PASSWD}#${DATABASE_NAME} <<EOF > $SQL_LOG/SITE_SQL.log
set echo off
set trimspool on
set pages 0
set linesize 1500
set feedback off
set head off
spool ${ETL_DIR}/SITE.txt
select LTRIM(RTRIM(COLUMN1))||'|'||LTRIM(RTRIM(COLUMN2)) from TABLE where COLUMN2 IN (${SITES});
exit
EOF
grep -i 'error' $SQL_LOG/SITE_SQL.log
if [ $? -ne 0 ]
then
echo "\n\n---------------------------->>`date`extraction successful\n\n---------------------------->>" >> $log
else
echo "\n\n---------------------------->>`date` Error with extraction from Table\n\n---------------------------->>" >> $log
exit -5
fi
But SITE_SQL.log which holds the log for database connectivity part is getting below error message in it.
ERROR:
ORA-28002: the password will expire within 13 days
which is making scripts to fail. but connecting happens to Database and we get required data in spool file. When script checks for error in log file SITE_SQL.log its failing. I dont want to change the error handling part but to suppress this message to be displayed/logged into logfile, so that script will not see this error message in logfile.
Also we have got a perl script which is facing same problem.Below is the code used.
my $l_Var_SQL_Statement="Select to_date('$Var_Data_Date_1','YYYY-MM-DD')-max(load_date) from TABLE where LOAD_STATUS='Success'";
$RetVal=SubExecuteSQL($Var_REP_TMP,$Var_USER_DB,$Var_USER_DBUSER,$Var_USER_DBPASSWORD,$l_Var_SQL_Statement);
if($RetVal eq "ERROR") {
$system_date=`date`;
chomp($system_date);
$Message="$system_date:Error Executing Query :$l_Var_SQL_Statement\n$system_date:Database Details:DB=$Var_USER_DB,Use
r ID=$Var_USER_DBUSER, Password= $Var_USER_DBPASSWORD for $my_filename Repository";
SubWriteLogMsg("$Var_REP_LOG","$Var_REP_LOGFILE","$Message");
$Message="Error Executing Query :$l_Var_SQL_Statement. Check log file for connection details.";
SubWriteMailMsg("$Var_INFA_MAILFOLDER","$Var_INFA_MAILFILE","$Message");
SubLogLoadAbort("$Var_REP_LOG","$Var_REP_LOGFILE","$Var_INFA_MAILFOLDER","$Var_INFA_MAILFILE");
exit -1;
}
Here since we are getting the password expiry alert error message SubExecuteSQL function is returning "ERROR" as return value which is making perl script to fail.
DBA's are not agreeing to set password does not expire option as its against security policy. Password is set to change every 60 days. so this error message will start popuping up and causing failure.
Please let me know how can i suppress this error message from getting/ logging into logfile.
Thanks in advance
Before your redirection to the log file, put a grep command in a pipe such as:
| grep -v '^\s*\(ERROR:$\|ORA-\)'
ie:
sqlplus -s ${USER_NAME}/${PASSWD}#${DATABASE_NAME} <<EOF | grep -v '^\s*\(ERROR:|ORA-)' > $SQL_LOG/SITE_SQL.log
Verify first that it works with a sample file: not all versions of grep support \s. If yours does not, use [ \t] instead (yes, the space character must be there, it's not a typo).

I want to prompt a user for the first 5 characters of a file then have it search for the files

I'm trying to write a script that will prompt the user for the first 5 charters of a file name then have it search the directories for any files that start with that. Then I want it to check to see if a folder is created with the file names and if not create one then move the files there. But if there is a directory for it already then to just move the files too the folder.
Break it down step by step:
"prompt the user for the first 5 characters of a file name" -- you can use the shell read command to get the data. Try a simple shell script:
#!/bin/bash
read foo
echo "foo = $foo"
"if a folder is created with the file names" -- you can use find to see if a file exists. for example:
find . -name abcde\*
"But if there is a directory for it already then to just move the files too the folder." -- the command mkdir takes a -p option so that, if the directory already exists, it won't do anything.