Remote Desktop Connection by making .bat file - windows

I want to connect my pc to another pc by making .bat file. When i run that file it should connect to the other pc. I wrote "mstsc /v:192.168.15.102" command when i execute this file it opens remote desktop window and demands username and password. How can i avoid that window and pass the credential in .bat file.

I found this
cmdkey /generic:TERMSRV/$server /user:$user /pass:$Password
mstsc /v:$Server
from archive (or original)
But I think that's for powershell only and I'm inexperienced with windows.
Along the comments I also saw this one:
For people that were looking for this idea but want to use batch instead I created the following. Save this a mstscup.cmd from notepad (don’t forget to remove the .txt at the end!)
Call it from the command line as follows:
mstscup “servername” “user” “pass”
I didn’t like the idea of leaving the user and pass in the password vault so it clears it after 120 seconds (leaves a command prompt window opened).
Feel free to modify at will!
#echo off
setlocal
:: Check if the user passed at least 1 argument
if “%1%” == “” (
echo Remoted Desktop connection with user and password
echo.
echo Missing arguments. Syntax:
echo %~nx0% “servername” “username” “password”
echo.
echo Jean Morin, v0.1, 2013-02-23
pause
goto :eof
)
:: Next line removes surrounding quotes from server name
set sServer=%~1%
:: Keep the quotes for the username and password (in case spaces exists)
set sUser=%2%
set sPass=%3%
:: Seconds to wait before clearing the newly added password from the vault (see control panel, manage your credentials)
:: You may want to modify this if the server takes longer to connect (WAN). You could add this as a fourth argument.
set sSeconds=120
:: Add a new connection definition method to the vault
cmdkey /generic:TERMSRV/%sServer% /user:%sUser% /pass:%sPass%
:: Connect to the server as a new task
start mstsc /v:%sServer%
:: ping ourselves for x seconds (acts like a pause) then removes the newly added password from the vault
ping -n %sSeconds% 127.0.0.1 >nul:
cmdkey /delete:TERMSRV/%sServer%

Best solution I could find was saving an rdp config.
Relatively much simpler than these options.
So open Remote Desktop Connection through start menu or win+r mstsc.exe.
Then select advanced options, change everything you want, and Save As.
This will create an .rdp file that can be clicked to run or run in command prompt.
:)

Remote Login using java and batch file by double click
Create batch file Remote.bat and write the following code,
#echo off
java Remote DEV
Create a java file Remote.java and write following code,
also change the IP address of your remote computer in code.
import java.awt.MouseInfo;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.concurrent.TimeUnit;
public class Remote
{
public static void main(String args[])
{
try
{
//showPosition();
System.out.println("Remote Desktop for-->"+args[0]);
String IP = "";
if("DEV".equalsIgnoreCase(args[0]))
{
IP = "mstsc /v:10.0.41.101";
}
else if("UAT".equalsIgnoreCase(args[0]))
{
IP = "mstsc /v:10.0.45.43";
}
else if("PRE-PROD".equalsIgnoreCase(args[0]))
{
IP = "mstsc /v:10.0.45.209";
}
Process p = Runtime. getRuntime(). exec(IP);
Robot bot = new Robot();
long mask = InputEvent.MOUSE_EVENT_MASK;
TimeUnit.SECONDS.sleep((long) 2.5);
bot.mouseMove(607, 290);
bot.mousePress((int) mask);
bot.mouseRelease((int) mask);
bot.keyPress(KeyEvent.VK_SHIFT);
bot.keyPress(KeyEvent.VK_Y);
bot.keyRelease(KeyEvent.VK_SHIFT);
bot.keyPress(KeyEvent.VK_E);
bot.keyPress(KeyEvent.VK_S);
bot.keyPress(KeyEvent.VK_B);
bot.keyPress(KeyEvent.VK_A);
bot.keyPress(KeyEvent.VK_N);
bot.keyPress(KeyEvent.VK_K);
bot.keyPress(KeyEvent.VK_1);
bot.mouseMove(765, 508);
bot.mousePress((int) mask);
bot.mouseRelease((int) mask);
}
catch (Exception e)
{
System.out.println("Exception send--->"+e.getMessage());
e.printStackTrace();
}
}
public static void showPosition() throws InterruptedException
{
try
{
while(true == true)
{
TimeUnit.SECONDS.sleep(1/2);
double mouseX = MouseInfo.getPointerInfo().getLocation().getX();
double mouseY = MouseInfo.getPointerInfo().getLocation().getY();
System.out.println("X:" + mouseX);
System.out.println("Y:" + mouseY);
//make sure to import
}
}
catch(Exception e)
{
System.out.println("Excpetion inside showPosition-->"+e.getMessage());
}
}
}
Now save the code and double click on Remote.bat.
it will automatically open your remote computer.
Enjoyyyyyyy

Related

How to use backup semantics (seBackup privilege) over the network?

I am trying to enumerate a directory on a remote file server.
I want to use backup-semantics in order to not require administrator credentials.
On the test server, I have created a share:
Share permissions: everyone full control
NTFS permissions: only SYSTEM (I removed all others)
I am currently using this code:
static void accessWithBackupSemantics() {
NetResource netResource = new NetResource() {
Scope = ResourceScope.GlobalNetwork,
ResourceType = ResourceType.Disk,
DisplayType = ResourceDisplayType.Share,
Usage = ResourceUsage.Connectable,
RemoteName = #"\\target-srv\TargetShare"
};
// open "net use" connection
int netResult = Native.WNetAddConnection2(netResource,
#"***password***",
#"DOMAIN\backup_op_user",
0);
if (netResult == 0 || netResult == 1219) {
// enable privileges
// (this is taken from AplhaFS)
using (new PrivilegeEnabler(Privilege.Backup)) {
try {
// try open remote directory
SafeFileHandle fsHandle = Native.CreateFile(
#"\\target-srv\TargetShare",
EFileAccess.GenericRead,
EFileShare.Read | EFileShare.Write,
IntPtr.Zero,
ECreationDisposition.OpenExisting,
EFileAttributes.BackupSemantics,
IntPtr.Zero);
Console.WriteLine("Handle is valid: " + !fsHandle.IsInvalid);
}
catch (Exception ex) {}
finally {
Native.WNetCancelConnection2(netResource.RemoteName, 0, true);
}
}
}
}
PrivilegeEnabler class is taken from AlphaFS
Native win32 structures and flags are taken from pinvoke.net/kernel32.createfile
This works if I specify "DOMAIN\Administrator" in the username, but does not work (the error is 5 - access denied) if I try to use a domain account that is a member of the local "Backup Operators" on target-srv server.
I have also examined the security event log on target-srv, for every connection created with WNetAddConnection2 a "Special Logon" event is written. The details of this event include the list of privileges that the logon account was given.
In both cases (when I connect with administrator or with backup_op_user) - seBackupPrivilege is indeed listed.
I tried to give extra privileges to the "Backup Operators" so the list has all the privileges that the Administrator has - but it made no change.
Questions:
What is the right way to use Backup-Semantics over the network?
How come it works with Administrator and not with a member of "Backup Operators" - are there additional implicit permissions for the Admin?
I have seen many examples of local use of Backup-Semantics, but not one that can be used over the network - please don't reply with links to examples of local usage.

InitiateShutdown fails with RPC_S_SERVER_UNAVAILABLE error for a remote computer

I'm trying to implement rebooting of a remote computer with InitiateShutdown API using the following code, but it fails with RPC_S_SERVER_UNAVAILABLE or 1722 error code:
//Process is running as administrator
//Select a remote machine to reboot:
//INFO: Tried it with and w/o two opening slashes.
LPCTSTR pServerName = L"192.168.42.105";
//Or use 127.0.0.1 if you don't have access to another machine on your network.
//This will attempt to reboot your local machine.
//In that case make sure to call shutdown /a /m \\127.0.0.1 to cancel it.
if(AdjustPrivilege(NULL, L"SeShutdownPrivilege", TRUE) &&
AdjustPrivilege(pServerName, L"SeRemoteShutdownPrivilege", TRUE))
{
int nErrorCode = ::InitiateShutdown(pServerName, NULL, 30,
SHUTDOWN_INSTALL_UPDATES | SHUTDOWN_RESTART, 0);
//Receive nErrorCode == 1722, or RPC_S_SERVER_UNAVAILABLE
}
BOOL AdjustPrivilege(LPCTSTR pStrMachine, LPCTSTR pPrivilegeName, BOOL bEnable)
{
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
BOOL bRes = FALSE;
if(!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
return FALSE;
if(LookupPrivilegeValue(pStrMachine, pPrivilegeName, &tkp.Privileges[0].Luid))
{
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Attributes = bEnable ? SE_PRIVILEGE_ENABLED : SE_PRIVILEGE_REMOVED;
bRes = AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
int nOSError = GetLastError();
if(bRes)
{
if(nOSError != ERROR_SUCCESS)
bRes = FALSE;
}
}
CloseHandle(hToken);
return bRes;
}
So to prepare for this code to run I do the following on this computer, which is Windows 7 Pro (as I would do for the Microsoft's shutdown tool):
Run the following "as administrator" to allow SMB access to the logged in user D1 on the 192.168.42.105 computer (per this answer):
NET USE \\192.168.42.105\IPC$ 1234 /USER:D1
Run the process with my code above "as administrator".
And then do the following on remote computer, or 192.168.42.105, that has Windows 7 Pro (per answer here with most upvotes):
Control Panel, Network and Sharing Center, Change Advanced Sharing settings
"Private" enable "Turn on File and Printer sharing"
Set the following key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
LocalAccountTokenFilterPolicy=dword:1
RUN secpol.msc, then go to Local Security Policy, Security Settings, Local Policies, User Rights Assignment. Add "Everyone" to "Force shutdown from a remote system". (Just remember to remove it after you're done testing!)
Note that the following shutdown command seems to work just fine to reboot the remote computer:
shutdown /r /m \\192.168.42.105 /t 30
What am I missing with my code?
EDIT:
OK. I will admit that I was merely interested in why InitiateShutdown doesn't seem to "want" to work with a remote server connection, while InitiateSystemShutdownEx or InitiateSystemShutdown had no issues at all. (Unfortunately the latter two did not have the dwShutdownFlags parameter, which I needed to pass the SHUTDOWN_INSTALL_UPDATES flag to, which caused my persistence...)
At this point I had no other way of finding out than dusting out a copy of WinDbg... I'm still trying to dig into it, but so far this is what I found...
(A) It turns out that InitiateSystemShutdownEx internally uses a totally different RPC call. W/o too many details, it initiates RPC binding with RpcStringBindingComposeW using the following parameters:
ObjUuid = NULL
ProtSeq = ncacn_np
NetworkAddr = \\192.168.42.105
EndPoint = \\PIPE\\InitShutdown
Options = NULL
or the following binding string:
ncacn_np:\\\\192.168.42.105[\\PIPE\\InitShutdown]
(B) While InitiateShutdown on the other hand uses the following binding parameters:
ObjUuid = 765294ba-60bc-48b8-92e9-89fd77769d91
ProtSeq = ncacn_ip_tcp
NetworkAddr = 192.168.42.105
EndPoint = NULL
Options = NULL
which it later translates into the following binding string:
ncacn_np:\\\\192.168.42.105[\\PIPE\\lsarpc]
that it uses to obtain the RPC handle that it passes to WsdrInitiateShutdown (that seems to have its own specification):
So as you see, the InitiateShutdown call is technically treated as Unknown RPC service (for the UUID {765294ba-60bc-48b8-92e9-89fd77769d91}), which later causes a whole bunch of credential checks between the server and the client:
which, honestly, I'm not sure I want to step into with a low-level debugger :)
At this stage I will say that I am not very well versed on "Local Security Authority" interface (or the \PIPE\lsarpc named pipe configuration.) So if anyone knows what configuration is missing on the server side to allow this RPC call to go through, I would appreciate if you could post your take on it?

How can one synchronize an external application with a DigitalMicrograph script?

This question has been inspired by the question 'Call script from command line'.
How can one write a script which acts on 'trigger events' in an application other than DigitalMicrograph?
i.e. some script functionality should be triggered by an external application.
The scripting language does not offer many 'external' interfaces in its current state. It is possible to call out to an external process with the command LaunchExternalProcess and wait for the process to complete, but there is no straight-forward way for an external process to call in, i.e. to start a script-action within DigitalMicrograph.
However, it is possible to work around that issue by using the system's file-system as a message queue. To do this, have a script running in the background which regularly checks if a certain file exists, and have the external application create such a file when it wants to trigger a scripting-action in DigitalMicrograph. The file content - if it is a simple text file - can also be used to transport information between the two applications.
Here is an example script which will wait until the file Trigger.txt appears in the root folder. The check is performed every 10seconds.
class WaitForExternal
{
string triggerFilePath
number taskID
void WaitOnTrigger( object self )
{
if ( DoesFileExist( triggerFilePath ) )
{
Result( GetTime(1) + ": Triggered! Now act..." )
If ( TwoButtonDialog( "Do you want to reset the trigger?", "Reset", "Stop" ) )
{
DeleteFile( triggerFilePath )
}
else
{
RemoveMainThreadTask( taskID )
}
}
else
{
Result( GetTime(1) + ": not yet\n" )
}
}
object Init( object self, string triggerPath, number waitSec )
{
triggerFilePath = triggerPath
taskID = self.AddMainThreadPeriodicTask( "WaitOnTrigger", waitSec )
return self
}
}
// Main script
{
string triggerPath = "C:\\Trigger.txt"
number pollingWait = 10
Alloc(WaitForExternal).Init( triggerPath, pollingWait )
}
Note that the periodic task waits idle in the background without interfering with the CPU, but the actual check is then performed on the main thread.

Windows programming - send email script

Looking for a simple script that would run on windows 2003 server that would basically send me an email. What I plan to do us the windows services auto recovery manager to trigger the script.
I did find a reference to how I can trigger the use of this script: How to monitor Windows services
But I need some help on writing an send email script that would work for windows platform. I'm not sure what language would be best for this. thanks.
One simple way would be to use javascript (or VBscript). If you google for "Server.CreateObject("CDO.Message")" you will find more examples.
Put the code below in a file with extension: ".js", for example email.js
To call use "cscript email.js" on the command line. Replace server name and emails with valid values.
Windows 2003 should have CDO installed. The script used to work on windows XP and server 2003. This example uses smtp server over the network but there are other options too.
Powershell is probably available for server 2003 .. so it could be another option.
============================== code ==============================
function sendMail ( strFrom, strTo, strSubject, strMessage ) {
try {
objMail = Server.CreateObject("CDO.Message");
objConfig = Server.CreateObject("CDO.Configuration");
objFields = objConfig.Fields;
with (objFields) {
Item("http://schemas.microsoft.com/cdo/configuration/sendusing")= 2;
Item("http://schemas.microsoft.com/cdo/configuration/smtpserver")= "xxxxsmtp.xxxserver.xxorg";
Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport")= 25;
Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 30;
Update();
}
with (objMail) {
Configuration = objConfig;
To = strTo; //"\"User\" ,"\"AnotherUser\" ;"
From = strFrom;
Subject = strSubject;
TextBody = strMessage;
//if we need to send an attachement
//AddAttachment("D:\\test.doc");
Send();
}
}
catch(e) {
WScript.Echo(e.message);
return false;
}
delete objFields;
delete objConfig;
delete objMail;
return true;
}
//WScript.Echo('qqq');
sendMail( 'from#xxxxxx.com', 'to#yyy.com' , 'test', 'msg');

problem in imagemagick and grails

i have a new problem in image magick that look strange ..
i'm using mac osx snow leopard and i've installed image magick on it and it's working fine on command ..
but when i call it from the grails class like the following snippet it gives me
"Cannot run program "convert": error=2, No such file or directory"
the code is :-
public static boolean resizeImage(String srcPath, String destPath,String size) {
ArrayList<String> command = new ArrayList<String>(10);
command.add("convert");
command.add("-geometry");
command.add(size);
command.add("-quality");
command.add("100" );
command.add(srcPath);
command.add(destPath);
System.out.println(command);
return exec((String[])command.toArray(new String[1]));
}
private static boolean exec(String[] command) {
Process proc;
try {
//System.out.println("Trying to execute command " + Arrays.asList(command));
proc = Runtime.getRuntime().exec(command);
} catch (IOException e) {
System.out.println("IOException while trying to execute " );
for(int i =0 ; i<command.length; i++) {
System.out.println(command[i]);
}
return false;
}
//System.out.println("Got process object, waiting to return.");
int exitStatus;
while (true) {
try {
exitStatus = proc.waitFor();
break;
} catch (java.lang.InterruptedException e) {
System.out.println("Interrupted: Ignoring and waiting");
}
}
if (exitStatus != 0) {
System.out.println("Error executing command: " + exitStatus);
}
return (exitStatus == 0);
}
i've tried normal command like ls and it's ok so the problem is that grails can't find convert command itself.. is it a os problem or something?
(see lower for the answer)
I have run into the same problem. The issue appears to be something with Mac OS X specifically, as we have several Linux instances running without error. The error looks similar to the following:
java.io.IOException: Cannot run program "/usr/bin/ImageMagick-6.7.3/bin/convert /a/temp/in/tmpPic3143119797006817740.png /a/temp/out/100000726.png": error=2, No such file or directory
All the files are there, and in chmod 777 directories - and as you pointed out, running the exact command from the shell works fine.
My theory at this point is that imagemgick can not load some sort of library itself, and the "no such file" is in reference to an dylib or something along those lines.
I have tried setting LD_LIBRARY_PATH and a few others to no avail.
I finally got this working. Here is how I have it setup. I hope this helps.
The crux of the fix, for me, was I wrapped the 'convert' into a shell script, set a bunch of environment variables, and then call that shell script instead of convert directly:
(convertWrapper.sh)
export MAGICK_HOME=/usr/local/ImageMagick-6.7.5
export MAGICK_CONFIGURE_PATH=${MAGICK_HOME}/etc/ImageMagick:${MAGICK_HOME}/share/doc/ImageMagick/www/source
export PATH=${PATH}:${MAGICK_HOME}/bin
export LD_LIBRARY_PATH=${MAGICK_HOME}/lib:${LD_LIBRARY_PATH}
export DYLD_LIBRARY_PATH=${DYLD_LIBRARY_PATH}:${MAGICK_HOME}/lib
export MAGICK_TMPDIR=/private/tmp
echo "$#" >> /private/tmp/m.log 2>&1
/usr/local/ImageMagick-6.7.5/bin/convert -verbose "$#" >> /private/tmp/m.log 2>&1
(convertWrapper.sh)
Additionally, the convert call was doing some rather complicated stuff, so I added the parameter '-respect-parenthesis' (which may or may not have had an effect).
I am not sure how much of the environment variable setting is needed as I was stabbing in the dark for a while, but since this is only for my development box...
You need to work out what your PATH is set to when you run a command from Java. It must be different to the one you have when running from the terminal.
Are you running Grails (via Tomcat?) as a different user? It might have a different path to your normal user.
you might want to try one of the Image Plugins that are part of the grails ecosystem
http://www.grails.org/ImageTools+plugin
the grails path when the app is running in the server is probably different from running java from the command line
I do so:
Put "convert" file to /usr/bin
Then add to Config.groovy:
gk {
imageMagickPath = "/usr/bin/convert"
}
Then in my ImageService.groovy:
import org.springframework.web.context.request.RequestContextHolder as RCH
[..]
def grailsApplication = RCH.requestAttributes.servletContext.grailsApplication
def imPath = grailsApplication.config.gk.imageMagickPath
def command = imPath + " some_properties"
def proc = Runtime.getRuntime().exec(command)
So this way you get command like: /usr/bin/convert some_properties
And it works, but don't forget to put file "convert" to you location and use it with this location.

Resources