Multiple Using AppleScript with administrator privileges - applescript

I have several commands that have to be run using admin:
Such as silently installing packages, creating folders as administrators, restarting some services, etc.
I think when using the administrator to run the shell command for the first time, after the user successfully enters the administrator password, it is no longer necessary for subsequent times.
I see similar questions not ask for authentication again for five minutes ,but not satisfied.
- (void)setUpScript {
// call this once
NSDictionary *error = nil;
NSString *copyScript = #"do shell script \"/bin/cp -r /Users/Simon/Desktop/Test/test.zip /Users/Simon/Desktop \" with administrator privileges";
self.myAppleScript = [[NSAppleScript alloc] initWithSource:copyScript];
}
- (void)runScript {
// call this as needed; shouldn't need reauthorization
if ([self.myAppleScript executeAndReturnError:&error]) {
NSLog(#"myAppleScript Success!");
} else {
NSLog(#"myAppleScript Failure!");
}
}
As i see this code.The variable "myAppleScript" it is fixed.I need to change its script content.But if I reinitialize "myAppleScript", the key window appears.Am I understanding it wrong?

The documentation: Technical Note TN2065 explains it clearly
Once a script is correctly authenticated, it will not ask for authentication again for five minutes.

Related

How can I redirect the standard output from cmd.exe

This has proven difficult to search as most results are all about redirecting from WITHIN cmd.exe rather than the output of cmd.exe itself.
I have a simple C# example showing a working and non-working test of redirecting process output and just printing the outputted values.
void Main()
{
// Calling nslookup directly works as expected
ProcessStartInfo joy = new ProcessStartInfo("nslookup", #"google.com 8.8.8.8");
// Calling nslookup as a command to cmd.exe does not work as expected
ProcessStartInfo noJoy = new ProcessStartInfo(Environment.ExpandEnvironmentVariables("%COMSPEC%"), #"/C nslookup google.com 8.8.8.8");
Console.WriteLine($"*** Running \"{joy.FileName} {joy.Arguments}\"...");
Console.WriteLine();
Run(joy);
Console.WriteLine();
Console.WriteLine($"*** Running \"{noJoy.FileName} {noJoy.Arguments}\"...");
Console.WriteLine();
Run(noJoy);
}
void Run(ProcessStartInfo startInfo)
{
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardOutput = true;
Process proc = new Process();
proc.StartInfo = startInfo;
proc.EnableRaisingEvents = true;
proc.Exited += ReceiveExitNotification;
proc.ErrorDataReceived += ReceiveStandardErrorData;
proc.OutputDataReceived += ReceiveStandardOutputData;
proc.Start();
proc.BeginErrorReadLine();
proc.BeginOutputReadLine();
proc.WaitForExit();
proc.ExitCode.Dump();
}
void ReceiveStandardOutputData(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data);
}
void ReceiveStandardErrorData(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data);
}
void ReceiveExitNotification(object sender, EventArgs e)
{
Console.WriteLine("Exited");
}
And here's the output I'm getting from the above
*** Running "nslookup google.com 8.8.8.8"...
Non-authoritative answer:
Server: dns.google
Address: 8.8.8.8
Name: google.com
Addresses: 2607:f8b0:4002:c08::8b
2607:f8b0:4002:c08::64
2607:f8b0:4002:c08::65
2607:f8b0:4002:c08::66
172.217.10.206
null
null
Exited
0
*** Running "C:\windows\system32\cmd.exe /C nslookup google.com 8.8.8.8"...
null
null
Exited
0
The choice of nslookup in the example is arbitrary, I've tried many others including commands with side effects so I can be sure it's being executed as expected.
I have tried with synchronous reads but no change.
I have no reason to believe it's C# or .NET related. I may try a direct CreateProcess() test to confirm.
For context, it's a batch file from which I'm actually looking to get the output, that's why the intermediate cmd.exe process is needed.
Further context, it's actually an MSBuild Exec task from which I'm trying to get the output, so I have limited control of the actual invocation, but I've watched the task run in the debugger and narrowed it down to this issue.
TLDR; The code example in the question works just fine on any normal machine.
So as it turns out this is a permissions issue. This is a company computer and I have restricted rights, however they have software installed that gives administrative rights to particular processes. cmd.exe is one of those processes, so by default it launches as admin and so I cannot read the output stream from my non-elevated process.
Some ideas that almost work around the issue:
From a cmd.exe prompt I can run set __COMPAT_LAYER=RUNASINVOKER then run a second cmd.exe which runs unelevated, but this doesn't really help as I still can't get that stream. Setting the __COMPAT_LAYER environment variable seems to only affect processes launched from cmd.exe (from not CreateProcess() which .NET's Process.Start() uses).
RunAs.exe has a /trustlevel switch with which I can run an unelevated command, but then my Process object is for runas which does not handle any redirection or even stay open for the life of the child process, so still no good.
But in my case I think the simplest solution is best. Copy cmd.exe to another directory and add that to the top of the path. This fixes the elevation issue and even works as a final solution to my actual problem by working event with my limited access to the invocation call through the MSBuild task.

Does $argv behave the same between Centos and RHEL systems

I am trying to troubleshoot an old TCL accounting script called GOTS - Grant Of The System. What it does is creates a time stamped logfile entry for each user login and another for the logout. The problem is it is not creating the second log file entry on logout. I think I tracked down the area where it is going wrong and I have attached it here. FYI the log file exists and it does not exit with the error "GOTS was called incorrectly!!". It should be executing the if then for [string match "$argv" "end_session"]
This software runs properly on RHEL Linux 6.9 but fails as described on Centos 7. I am thinking that there is a system variable or difference in the $argv argument vector for the different systems that creates this behavior.
Am I correct in suspecting $argv and if not does anyone see the true problem?
How do I print or display the $argv values on logout?
# Find out if we're beginning or ending a session
if { [string match "$argv" "end_session"] } {
if { ![file writable $Log] } {
onErrorNotify "4 LOG"
}
set ifd [open $Log a]
puts $ifd "[clock format [clock seconds]]\t$Instrument\t$LogName\t$GroupName"
close $ifd
unset ifd
exit 0
} elseif { [string match "$argv" "begin_session"] == 0 } {
puts stderr "GOTS was called incorrectly!!"
exit -1
}
end_session is populated by the /etc/gdm/PostSession/Default file
#!/bin/sh
### Begin GOTS PostSession
# Do not run GOTS if root is logging out
if test "${USER}" == "root" ; then
exit 0
fi
/usr/local/lib/GOTS/gots end_session > /var/tmp/gots_postsession.log 2> /var/tmp/gots_postsession.log
exit 0
### End GOTS PostSession
This is the postsession log file:
Application initialization failed: couldn't connect to display ":1"
Error in startup script: invalid command name "option"
while executing
"option add *Font "-adobe-new century schoolbook-medium-r-*-*-*-140-*-*-*-*-*-*""
(file "/usr/local/lib/GOTS/gots" line 26)
After a lot of troubleshooting we have determined that for whatever reason Centos is not allowing part of the /etc/gdm/PostSession/default file to execute:
fi
/usr/local/lib/GOTS/gots end_session
But it does update the PostSession.log file as it should .. . Does anyone have any idea what could be interfering with only part of the PostSession/default?
Does anyone have any idea what could be interfereing with PostSession/default?
Could it be that you are hitting Bug 851769?
That said, am I correct in stating that, as your investigation shows, this is not a Tcl-related issue or question anymore?
So it turns out that our script has certain elements that depend upon the Xserver running on logout to display some of the GUI error messages. This from:
Gnome Configuration
"When a user terminates their session, GDM will run the PostSession script. Note that the Xserver will have been stopped by the time this script is run, so it should not be accessed.
Note that the PostSession script will be run even when the display fails to respond due to an I/O error or similar. Thus, there is no guarantee that X applications will work during script execution."
We are having to rewrite those error message callouts so they simply write the errors to a file instead of depending on the display. The errors are for things that should be there in the beginning anyway.

Multiple script commands through SSH on Juniper OS

My question is concerning networking equipments, especially Juniper OS.
I would like to execute a lot of commands through SSH on the switch.
And not manually, with a script.
But, when I push a command through SSH (example : 'configure') to manipulate software configuration, it changes the prompt indeed.
And the next command, available only in this level of configuration, doesn't work, because the level up is for sure not registrated since last command, so new command = come back to inital prompt.
Example in Ruby with net/ssh :
ssh = Net::SSH.start("X.X.X.X", LOGIN, :password => PASSWORD)
ssh.exec!("configure") # -> Entering configuration mode
ssh.exec!("set system services telnet") # -> error: unknown command: set
ssh.close
On Juniper ILC, there isn't '&' or ';' to add mutlipe commands.
Is it possible to insert a carriage return in this kind of command and then put all commands in one request ?
Otherwise how can I execute several commands, keeping the link between them ?
Thanks in advance.
Ok, the only solution I found is to concatenate the instructions into one connection.
Example :
ssh.exec!('configure;
set system services telnet;
delete system services web-management;
set system login class READ permissions view-configuration;
set system login class READ allow-commands show;
...
commit;')
Hope this will help somebody, don't hesitate to improve it !
I know it's about Ruby but i hope my investigation results in Java could be useful. I used construction like this in eBay/parallec(i think in JSch it'll work too) :
public static void sshVmWithPassword() {
ParallelClient pc = new ParallelClient();
pc.prepareSsh().setTargetHostsFromString(HOST)
.setSshCommandLine("show version;\nshow log")
.setSshUserName(USERNAME)
.setSshPassword(PASSWORD)
.execute(new ParallecResponseHandler() {
public void onCompleted(ResponseOnSingleTask res,
Map<String, Object> responseContext) {
System.out.println("Responose:" + res.toString()
+ " host: " + res.getHost()
+ " errmsg: " + res.getErrorMessage());
}
});
pc.releaseExternalResources();
}

security find-generic-password command for safari returning some garbage value

I want to find the Safari Extensions List password from the keychain. I am doing it through NSTask now, As soon as we launch the task, it is printing some password. But When I store the password in some NSString using,
NSString * password = [[NSString alloc] initWithData:dataRead encoding:NSASCIIStringEncoding];
it is returning some other value. Is there any other way to read the output of NSTask/NSPipe?
If you already have NSData* dataRead from "Safari Extensions List", just save it to a file:
[dataRead writeToFile:#"/tmp/extensions_list.plist" atomically:YES];
Got the answer
There are two ways to find the safari password from the keychain.
1. Using API
status = SecKeychainFindGenericPassword(
NULL, // default keychain
service_length, // length of service name
cService_name, // service name
username_length,// length of account name
cUser_name, // account name
&passwordLength, // length of password
&passwordData, // pointer to password data
NULL // the item reference
);
Here Service name is Extended Preferneces and username is Safari.
Using NSTask or Terminal :
[task setArguments:[NSArray arrayWithObjects:#"find-generic-password",#"-g",#"-l", #"Safari Extensions List", nil]];
Terminal Command is
security find-generic-password -l "Safari Extensions List" -g
Copy the Hexadecimal password from the ouput of the above command, delete 0x prefix from the password, convert it to NSData and then use NSPropertyListSerialization propertyListWithData method, we can see the Safari Extensions List along with its enabled state.

Configure registry permission tool

I have to write a key value pair in the registry. This is done using a tool. This fails sometimes.
Is there any windows utility available which can set the permissions of the registry? If the specific user does not have permission to the registry, I should be able to configure the permissions accordingly - from an administrator account.
I have the only option of invoking it during system startup to set the parameters.
try this
bool flag1 = false;
try
{
new System.Security.Permissions.RegistryPermission(System.Security.Permissions.PermissionState.Unrestricted).Assert();
// Your Work
}
catch (Exception obj1) //when (?)
{
}
finally
{
System.Security.Permissions.RegistryPermission.RevertAssert();
}
return flag1;
Look at the Regini.exe tool. See here for more details: How to change registry values or permissions from a command line or a script

Resources