Assistance needed with vbs to change Admin Account - authentication

I've been tasked with creating a vbs to do the following:
If NewAdmin exists then Set password for NewAdmin and disable Local Administrator account
Else Rename local Administrator account to NewAdmin and set password.
Thanks again for the quick reply. I have changed the code below accordingly and am now trying to use the Windows Script Encoder to obfuscate the password. I understand that there is still a risk involved as this could be decoded, but the script will not be stored on the user's computer and as such will not pose much of a threat.
The code now shows the three added lines needed for the Windows Script Encoder to do it's job, but I can't get it to work. I run the following command from the command line:
screnc /l vbscript admin_script.vbs admin_script.vbe
It creates the admin_script.vbe successfully. But then when I attempt to run the encoded script it presents the following error message:
Script: C:\...\admin_script.vbe
Line: 2
Char: 1
Error: Expected Statement
Code: 800A0400
Source: Microsoft VBscript compilation error
The unencoded script runs without issues. I have tried another method to encode the data using a vbscript I located online, but it does the same thing ... obfuscates the data but the script doesn't work afterwords. I also read that it may be an encoding issue and that I needed to save the vbs as UTF-8 without BOM but that didn't work either.
If anyone knows how to get this Windows Script Encoder working I would greatly appreciate it. Also, if there is another method for encrypting / obfuscating the code, any suggestions are welcome. I will say that I'm not a big fan of creating an executable from VBS, but will resort to that if necessary.
<SCRIPT LANGUAGE="VBScript">
'**Start Encode**
OPTION EXPLICIT
DIM objNetwork, objUser, objComputer
DIM strPassword, strAdminUserName, strNewAdminUserName, strComputer, strUser
' Get Computer Name and make it all uppercase
SET objNetwork = CREATEOBJECT("Wscript.Network")
strComputer = UCASE(objNetwork.ComputerName)
' Setting veriable for IF statement
strUser= "NewAdmin"
' The old name of the administrator user account (normally administrator)
strAdminUserName = "Administrator"
' The new name of the administrator user account
strNewAdminUserName = "NewAdmin"
' New Password for administrator account.
strPassword = "passwordhere"
On Error Resume Next
Set objUser = GetObject("WinNT://" & strComputer & "/" & strUser & ",user")
If (Err.Number = 0) Then
On Error GoTo 0
' Set password of admin user account
setPWD strComputer,strNewAdminUserName,strPassword
' Disable Local Administrator account
Set objUser = GetObject("WinNT://" & strComputer & "/Administrator, user")
objUser.AccountDisabled = True
objUser.SetInfo
Else
On Error GoTo 0
' Rename admin user account
renameUser strComputer,strAdminUserName,strNewAdminUserName
' Set password of admin user account
setPWD strComputer,strNewAdminUserName,strPassword
End If
' enter code hereReset password for a local user account on a given computer
SUB setPWD(strComputer,strUser,strPassword)
DIM objUser
' Ignore error if user account isn't found or error changing password
ON ERROR RESUME NEXT
SET objUser = GETOBJECT("WinNT://" & strComputer & "/" & strUser & ",user")
IF err.number = 0 THEN
objUser.SetPassword strPassword
objUser.SetInfo
END IF
ON ERROR GOTO 0
END SUB
' Rename a local user account on a given computer
SUB renameUser(strComputer,strFromName, strToName)
DIM objComputer,objUser
' Ignore error if user account isn't found or error moving user
ON ERROR RESUME NEXT
SET objComputer = GETOBJECT("WinNT://" & strComputer)
SET objUser = GETOBJECT("WinNT://" & strComputer & "/" & strFromName & ",user")
IF err.number = 0 THEN
objComputer.MoveHere objUser.ADsPath,strToName
END IF
ON ERROR GOTO 0
END SUB
</SCRIPT>

change this
If (Err.Number <> 0) Then
to this
If (Err.Number = 0) Then

Related

Word VBA MkDir Invalid Path in Sharepoint

I am trying to use VBA to create a folder within Sharepoint at my work. The document is opened from Sharepoint so there should be no credential issues (I would think).
I have tried all of the following and always get Run-time error '76': Path not found
How .Path reads the document's location (having removed the document obviously)
MkDir "https://company.sharepoint.com/directory/directory with spaces"
Without certificate
MkDir "//company.sharepoint.com/directory/directory with spaces"
With backslashes between directories
MkDir "https://company.sharepoint.com\directory\directory with spaces"
With corrected spaces
MkDir "https://company.sharepoint.com/directory/directory%20with%20spaces"
and most combinations of the above.
I noted that it takes much longer for Word to decide it's an invalid path without certificate.
I cannot post the actual paths due to NDA issues, but the above recreation should have all pertinent possible issues within the path. I am not parsing the path from variables or input (though I will later) and they are held within a private sub.
I appreciate any help you can give.
Okay, this took me far longer to complete than I expected. I essentially just grabbed the solution from the link in my first comment link I above and added error handling so that (hopefully) all scenarios have a good exit point and explanation.
Sub SharepointAddFolder()
Dim filePath As String
filePath = "https://web.site.com/SharedDocuments/Folder"
'filePath = Replace(filePath, "https:", "") 'I didn't need these but who knows
'filePath = Replace(filePath, "/", "\")
'filePath = Replace(filePath, " ", "%20")
Dim newFolderName As String
newFolderName = "New Folder"
Dim driveLetter As String
driveLetter = "Z:"
Dim ntwk As Object
Set ntwk = CreateObject("WScript.Network")
On Error GoTo ErrHandler
ntwk.MapNetworkDrive driveLetter, filePath, False ', "username", "password"
If Len(Dir(driveLetter & "/" & newFolderName, vbDirectory)) = 0 Then
MkDir driveLetter & "/" & newFolderName
Else
MsgBox "Folder " & newFolderName & " already exists."
End If
ExitThis:
ntwk.RemoveNetworkDrive driveLetter
Exit Sub
ErrHandler:
Select Case Err.Number
Case -2147024829
MsgBox "Sharepoint site not found"
Case 76
'sharepoint directory not found
MsgBox "Mapping failed"
Case -2147024811
'drive already mapped
Resume Next
Case -2147022646
'drive not found and thus cannot be closed
Case -2147022495
MsgBox "This network connection has files open or requests pending." & vbNewLine & vbNewLine & _
"Either close the files or wait until the files are closed, then try to cancel the connection."
Case Else
MsgBox "Error " & Err.Number & ": " & vbNewLine & Err.Description
End Select
End Sub
Note for those of you desiring to continue to work on temporarily mapping SharePoint drives: this code work without any need for username or password (My company uses Authenticator), but only once you have logged in to SharePoint using Internet Explorer. I learned that, when using IE, an option under “All Documents” called “View in File Explorer” exists. It does not exist for Chrome or other browsers (as far as I know). My intent was to permanently map the drives, but once I had logged in from IE the code worked. You do not even have to stay logged in to IE and, when you return to the SharePoint via IE, you are still logged in (I have done this over a one day no-use period). I assume this something to do with the IE being a Microsoft product and therefore being trusted to keep login credentials.

How to overcome CATIA.FileSelectionBox() error without setting "regserver option" as administrator?

The following code runs well if I have administrator permissions. But it doesn't work at all for a user.
Sub CATMain()
On Error Resume Next
Dim strpath As String
strpath = CATIA.FileSelectionBox("Select file", "*.xlsx",
CatFileSelectionModeOpen)
End Sub
I think CATIA.FileSelectionBox() works fine in CATScript so I was thinking in run a CATScript with Application.ExecuteScript(). When I try to do it another error pops up "Function or interface marked as restricted...". Can anyone give me an alternative method? Would be very much appreciated.
Ok, I found my answer. Thanks for letting me post my question in here. Next, I post a code that works just fine. The only thing that remains incomplete is that I can not add filters for types of files like *.CATParts or *.CATProducts in this code. But it works for me already.
Function SelectFile( )
' File Browser via HTA
' Author: Rudi Degrande, modifications by Denis St-Pierre and Rob van der
Woude
' Features: Works in Windows Vista and up (Should also work in XP).
' Fairly fast.
' All native code/controls (No 3rd party DLL/ XP DLL).
' Caveats: Cannot define default starting folder.
' Uses last folder used with MSHTA.EXE stored in Binary in
[HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32].
' Dialog title says "Choose file to upload".
' Source: https://social.technet.microsoft.com/Forums/scriptcenter/en-
US/a3b358e8-15ae-4ba3-bca5-ec349df65ef6/windows7-vbscript-open-file-dialog-
box-fakepath?forum=ITCG
Dim objExec, strMSHTA, wshShell
SelectFile = ""
' For use in HTAs as well as "plain" VBScript:
strMSHTA = "mshta.exe ""about:" & "<" & "input type=file id=FILE>" _
& "<" & "script>FILE.click();new
ActiveXObject('Scripting.FileSystemObject')" _
&
".GetStandardStream(1).WriteLine(FILE.value);close();resizeTo(0,0);" & "<" &
"/script>"""
' For use in "plain" VBScript only:
' strMSHTA = "mshta.exe ""about:<input type=file id=FILE>" _
' & "<script>FILE.click();new
ActiveXObject('Scripting.FileSystemObject')" _
' &
".GetStandardStream(1).WriteLine(FILE.value);close();resizeTo(0,0);
</script>"""
Set wshShell = CreateObject( "WScript.Shell" )
Set objExec = wshShell.Exec( strMSHTA )
SelectFile = objExec.StdOut.ReadLine( )
Set objExec = Nothing
Set wshShell = Nothing
End Function
Kind regards

VBA Excel SSO to SAP / runtime error 70 "access denied"

I spend hours finding the problem.
I want to start the SAP Logonpad with the ini file, that works fine.
Then after binding to the scripting object I want to open the connection to a specific System with connection = SapGui.OpenConnection("SID", True)
but always get runtime error 70 access denied.
I followed what others seem to do with vbs, for certain resons I can't do it with vbs and have to go with vba, so maybe there might be some difference that makes it fail?
Any advice would be highly appreciated.
Private Sub CommandButton1_Click()
Dim SapGui As Object
Dim saplogon As Object
Dim connection 'As Object
Set SapGui = GetObject("SAPGUI")
Dim Wshshell As Object
Set Wshshell = CreateObject("Wscript.Shell")
Wshshell.Run Chr(34) & ("C:\Program Files\SAPPC\FrontEnd\SAPgui
\saplogon.exe") & Chr(34) & " " & "/INI_FILE" & "=" & Chr(34) &
"\\longpathtoini\appl\Sap\saplogon\int\saplogon.ini" & Chr(34)
Do Until Wshshell.AppActivate("SAP Logon")
Application.Wait Now + TimeValue("0:00:01")
Loop
Set Wshell = Nothing
Set saplogon = SapGui.GetScriptingEngine
connection = SapGui.OpenConnection("SID", True)
Set SapGui = Nothing
Set saplogon = Nothing
Set connection = Nothing
End Sub
Check whether user scripting is allowed for the particular system (transaction RZ11, parameter sapgui/user_scripting). Also be aware that for some versions, you'll apparently need to specify the SAP Logon entry text instead of the SID.
Thanks to vwegert.
I surely knew about scripting needs to be enabled on the servers.
Which is, but at the moment I read his answer I remembered that in my SAP GUI settings the checkbox for "Warn if a script tries to connect" was enabled.
Disabeling that options did lead to success.
The above code works perfectly.

Get logged on username in Excel VBA - not the account running Excel (using RunAs)

I have logged into my workstation with my normal domain credentials. We shall call this AccountA.
I then use the "run as a different user" to launch Excel. We shall call this AccountB. I do this because the permissions needed to query some SQL servers must be done using AccountB.
At this point, I need to include a subroutine to launch a Shell to create directories and move files on a remote server. AccountB doesn't have (and cannot have) permissions to do this. My shell gives me an Access Denied message. Fine.
So now, I need to have VBA return the name of AccountA, the account I have used to log into the computer. How do I do this?
I have seen quite a few examples on this site as well as others that will return the username running Excel (AccountB). However, I have not seen any examples that will pull AccountA information to pass to the Shell via RunAs to carry out my commands with the proper permissions. Below are some things I have tried, all returning AccountB (the account used via RunAs to launch Excel)
This application will be used by multiple people with permissions to run cmd shell on the remote server, so AccountA cannot be hardcoded and must be programmatically obtained.
' Access the GetUserNameA function in advapi32.dll and
' call the function GetUserName.
Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" _
(ByVal lpBuffer As String, nSize As Long) As Long
Sub XXXXXXXXXX()
'//
ThisWorkbook.Sheets("XXXXXXXXXX").Activate ' select the worksheet for use
cmdString = UCase(Trim(ThisWorkbook.ActiveSheet.Cells(4, 4).Value)) 'get XXXXXXXXXX
'MsgBox cmdString
'retval = Shell("cmd.exe /k " & cmdString, vbNormalNoFocus)
'cmdString = "MkDir \\XXXXXXXXXX\g$\Tempski" 'fails - no permission
'Set the Domain
txtdomain = "XXXXXXXXXX"
'Acquire the currently logged on user account
'txtuser = "XXXXXXXXXX"
' Dimension variables
Dim lpBuff As String * 255
Dim ret As Long
' Get the user name minus any trailing spaces found in the name.
ret = GetUserName(lpBuff, 255)
If ret > 0 Then
GetLogonName = Left(lpBuff, InStr(lpBuff, Chr(0)) - 1)
Else
GetLogonName = vbNullString
End If
MsgBox GetLogonName
Dim objNet As Object
On Error Resume Next
Set objNet = CreateObject("WScript.NetWork")
MsgBox "Network username is: " & objNet.UserName
Set objNet = Nothing
MsgBox "Environ username is: " & Environ("USERNAME")
MsgBox "Application username is: " & Application.UserName
MsgBox "Network username is: " & WindowsUserName
Dim strUser As String
strUser = ActiveDirectory.user()
MsgBox "Welcome back, " & strUser
CurrentWorkbenchUser = Environ("USERDOMAIN") & "\" & Environ("USERNAME")
MsgBox CurrentWorkbenchUser
Set WSHnet = CreateObject("WScript.Network")
UserName = WSHnet.UserName
UserDomain = WSHnet.UserDomain
Set objUser = GetObject("WinNT://" & UserDomain & "/" & UserName & ",user")
GetUserFullName = objUser.FullName
MsgBox GetFullUserName
'//try to pass user credentials to shell - service account cannot run XXXXXXXXXX
'//This Works when txtdomain and txtuser are passed properly (MUST GRAB THESE SOMEHOW)
'retval = Shell("runas /user:" & txtdomain & "\" & txtuser & " ""cmd.exe /k dir /s *.*""", vbNormalFocus)
End Sub
All the bits of code above return the account used to launch Excel — not what I need i.e. the account I used to log into the computer.
The basic approach is to execute the shell with a "run as" parameter.
have you taken a look at this
also look here
This is code ripped from the ms sight and is just here to make sure that the next guy or gal who comes by has a quick reference.
Sub RegisterFile(ByVal sFileName As String)
ShellExecute 0, "runas", "cmd", "/c regsvr32 /s " & """" & sFileName & """", "C:\", 0 'SW_HIDE =0
End Sub
As an aside if you only need the account for access to a SQL server, you should be able to just set the account within the connection string in your vba MACRO. I've done that for an Oracle DB in the past.

Ping server process is hanging

I am trying to ping a server before uploading a file with ftp. Recently, a client complained that the process was freezing. I tested the ping process with a vbscript file just to make sure something wasn't broken on the computer. The vbscript worked just fine. So I ran the script from the Access database and it hung just the same as it did before. Is there something about the ping exe that I am missing here?
Vbscript that runs just fine when you double click it.
Const fsoForWriting = 2
Dim oShell, ping, strPath, strPing
Set oShell = WScript.CreateObject ("WScript.Shell")
Set ping = oShell.exec("ping -n 2 -w 750 google.com")
Do While ping.Status = 0
WScript.Sleep 100
Loop
strPing = ping.StdOut.ReadAll
strPath = Wscript.ScriptFullName
Set objFSO = CreateObject("Scripting.FileSystemObject")
strTextFile = objFSO.GetParentFolderName(strPath) & "\PingResults.txt"
Set objTextStream = objFSO.OpenTextFile(strTextFile, fsoForWriting, True)
objTextStream.WriteLine strPing
objTextStream.Close
Set objTextStream = Nothing
Set objFSO = Nothing
Set oShell = Nothing
VBA function that runs on the test database on startup. This is the code that hangs.
Function fFtpOnline(ByVal ComputerName As String)
On Error GoTo ErrHandler
Dim oShell, ping
Set oShell = CreateObject("WScript.Shell")
Set ping = oShell.exec("cscript " & Access.CurrentProject.Path & "\" & "Test.vbs")
Do While ping.Status = 0
DoEvents
Loop
Set oShell = Nothing
Exit Function
ErrHandler:
MsgBox Err.Description & " " & "fFtpOnline "
Resume Next
End Function
This code works fine on my computer but on the client's computer, the code hangs.
This may sound like a rude answer, but by no means is it intended to be. Just as the comment above stated, this is more than likely it issue on your customer's end. If the program works currently on your end and not theirs they have the issue, not the code. I've run into plenty of customers who are clueless so unless they are willing to let you take control of their machine remotely I would recommend them capturing some information for you. ipconfig is a good place to start. And while they are at the command prompt have them try to ping some places. I know this is not a true answer, but it is what I have encountered in the past.