Tag: cmd

  • Introduction to the Utility Robocopy

    Introduction to the Utility Robocopy

    Introduction

    Robocopy (Robust Copy) is a command line tool for copying files in Windows. It replaces the older ‘copy’ command. It contains many new features and can copy files both to an external hard drive or a remote computer.

    Before you can copy files to an external hard drive, you need to create a folder on the destination drive first and set the permission on that folder to ‘Everyone’ (see below). I like to somewhat mirror the folder structure of the source and destination files. It makes for an easy reference, when you need to look for the files on the backup.

    Command Layout

    The three primary copy switches are /E, /S, and /MIR. They will copy just the data, attributes, and timestamps (/COPY:DAT), and not file permissions. The default behavior (not using any switches) of robocopy is to copy only newer files and overwrite the older files at the destination.

    The basic format of the command.

    If you are copying files you are not the owner of, you will need to run the the command prompt as an Administrator and use the /B switch to override the file and folder permissions. You will typically want to use the /Z if coping files over a network and you want to exclude Hidden and System files. The /TEE switch is only necessary if it is an attended backup. Finally, I like to drop a log file in the backup folder in case I need to review anything.

    Copy Switches

    • /L Test the command before you execute it.
    • /S Do not copy empty directories.
    • /E Copy all directories, including empty ones.
    • /MIR Sync a directory. (Caution! If a file is deleted in source, will be deleted in destination).
    • /B Copy in backup mode. Copy all files regardless of permissions. (Needed if copying files other than your own. Run command prompt as an Administrator).

    Network Switches

    • /Z Use Restart mode, Start copy where you left off. (Needed when possible network interference).
    • /ZB Use Restart mode & Backup mode. (Needed when coping over a network).
    • /W:2 Wait time between retries. (Needed when copying over a network).
    • /R:1 The number of retries, if the file is locked. (Needed when coping over a network).

    Exclude Switches

    • /XA:H Exclude files with the attribute Hidden. (Typically want to use this switch)
    • /XA:S Exclude files with the attribute System. (Typically always want to use the switch).
    • /XA:SH Exclude System and Hidden files (Needed when coping a User’s Profile).
    • /XJ exclude junction points. (Needed when coping a User’s Profile).
    • /FTT format in FAT32 File system. (Needed if backing up files to a Linux host).
    • /XD exclude directory. Use if you want to exclude some Hidden files and not others.

    Logging Switches

    • /NFL Don’t log file names of copied files.
    • /NDL Don’t log directory names. (Include if using a log file).
    • /NP Suppress % copied output to a log file. (Include if using a log file).
    • /LOG:/F:\backup.log Writes output to a log file.
    • /LOG+:F:\file.log Append output to an existing log file.
    • /TEE Write output to the console window AND the log file.

    Get Help

    Copy Files to an External Drive

    Copy one or two files. If you have spaces in the file path, be sure to enclose in quotes.

    Copy files that end with pdf or begin with Sam. The * is a wildcard.

    robocopy "C:\users\username\desktop\folder 1" "D:\backup\folder 2" *.pdf
    robocopy "C:\users\username\desktop\folder 1" "D:\backup\folder 2" Sam.*

    Copy all files & folders on the desktop, & make a log file. Also, show the results on the screen as the command is running.

    Copy a user’s profile (MIR), exclude the junction points (XJ), system files (XA:S), and the user’s “AppData” folder (XD). Suppress the percent copied results (NP). Junction points are a kind of soft link or a shortcut. The copy process could get stuck in a copy loop if you do not exclude. This will still copy any other hidden files. Output results to screen and log file (TEE & LOG).

    robocopy "C:\Users\John" "D:\backup\Users\John" /MIR /XA:S /XD "c:\Users\John\AppData" /XJ /TEE /NP /LOG:F:\backup\backup.log

    Copy Files to a remote PC

    Copy a directory, subdirectories, and files to a remote computer.

    Copy a directory, subdirectories, and files, but excluding system & hidden files, to a remote Linux PC.

    Step-By-Step Guide to Backup Your Files

    Begin by plugging in a USB stick into any open port on the PC. In our example, it shows up as “Drive F”. Now, make a new folder called F:\backups.

    Set the permissions on the new folder to ‘Everyone’ by right clicking on the folder, go to properties, security tab, select add group or username, and select check names. Be sure to verify that the “Everyone” has all the allow permissions.

    Now, any folders or files copied to the “backup” folder during the backup, should inherit the same permissions. (i.e. Everyone).

    If you don’t do this and you need to access the files on a PC other than the original computer, you may not be able to open the files. This is because you are not logged in as the original user that ran the backup. But, with folder permissions set to Everyone, you can plug the external drive or USB stick into any computer, and you will have full access to the copied files.

    Make a Backup Script

    We will backup the contents of a generic folder and two user’s profiles. It will copy to an external hard drive and also to a remote windows computer. For this example, we are logged in as a user called Jack and it is an “admin” account, so we can be granted rights to copy files of other users.

    First, we will start by coping all files in a folder called “Data”. Since we don’t know who owns this folder, we will use the /B switch to overwrite any potential permissions issues. Finally, we will make a log file but exclude the percent copied for each file. As this unnecessary clogs up the log output.

    Next, we can now copy Jack and Jill’s profiles. Jack’s profile, we will exclude all hidden files, system files, and junction points. Since his “AppData” folder is already hidden, we do not need to specifically exclude it.

    In Jill’s profile, we have several hidden files that we want to copy that contain her SSH keys. So, we will not create a blanket exclusion for all hidden files. Instead, we will exclude her “AppData” folder specifically. Finally, we will add to the previously created log file, but again we will exclude the total percent copied. Also, we need to add her file using the /B switch to copy in backup mode.

    robocopy C:\Users\Jack F:\backups\Jack /MIR /XA:SH /XJ /NP /LOG+:F:\backup.log
    robocopy C:\Users\Jill F:\backups\Jill /MIR /XA:S /XD C:\Users\John\AppData /B /XJ /NP /LOG+:F:\backup.log

    Finally, copy the same files to a remote computer for a secondary backup. As before, we will use the /MIR switch to make an exact duplicate folder tree, /B to run in backup mode and exclude the System, Hidden, Junction Points, and specifically exclude Jill’s “AppData” folder. Also, we use the /Z (restart mode), /R (retry) and /W (wait) in case there are network issues.

    Save and Execute the Script

    Save the script to Jack’s desktop as backup.bat. To run the script, open a command prompt as an Admin, and navigate to Jack’s desktop. Type the script name and hit enter. To run the script nightly, you can set up a scheduled task to execute.

    References

    https://ss64.com/nt/robocopy.html

    http://caughtinpixels.com/how-to-create-a-backup-script-using-robocopy/

  • Tracking Communications with Netstat & TCPView

    Tracking Communications with Netstat & TCPView

    Netstat on the Command Line

    Netstat is a built in utility typically used to troubleshoot remote connection issues. It is also be used to see what external IPs and URLs your computer is actively communicating with and to what ports are passively open waiting for a connection. To run netstat, launch the Command Prompt in administrator mode.

    It is important to remember that running the command is a one and done. It does not auto refresh unless you tell it to using a switch. To get a list of switches, run “netstat /?“. The most important for netstat switches are:

    -a = Display all connections and listening ports
    -b = Display the executable involved.
    -f = Display FQDN.
    -n = Display IP and ports in number format.
    -o = Display process ID associated with the connection.
    -r = Display routing table.

    Let’s go over some commands. First, ‘netstat -ab’ is unusually slow to provide results and the results are not in a easy to read format. For this reason many users do not like it. But it will provide the process name that opened or established the connection.

    Next is ‘netstat -ano’. It provides very fast results, but does not provide the name of the running service. However, you can get the process ID’s and then lookup the running process in task manager to find the service or executable. Finally, you can lookup up the foreign addresses in an online URL lookup to find the ‘whois’ or the IP registration.

    Display the TCP active connections with the FQDN.

    You can pipe the results from netstat to include only specific outputs.

    You can pipe to exclude results by using the /V switch.

    Using TCPView

    Think of TCPView (or the older CURRPorts) as a netstat GUI interface. TCPView is produced by Microsoft System Internals and is actively supported. It is easier to read then the command line, auto refreshed every 2 seconds, and provides both fast results as well as the process name.

    You can quickly track down what service is attempting to make an external connection, what remote IP or URL it is communicating with, and over what port. The results can be combined with some google searches to get a complete picture. I find it easier than trying to interpret the netstat command line results.

    The color scheme is tricky. Red means a connection is about to close, green means a connection was just opened, and yellow means a connection has just refreshed. Notice the green bar in the picture below.

  • Change Windows Cmd Line Startup Folder

    Change Windows Cmd Line Startup Folder

    Change Default Startup Path for Command Prompt

    Right click on the command prompt then select properties. On shortcut tab, change “Start in:”

  • Top Windows Terminal Commands

    Top Windows Terminal Commands

    Introduction

    Although PowerShell has made progress over the last few years as the preferred command line tool, I find that knowledge of the original command line is still very valuable. You can use the command line to quickly get system information or write batch scripts to automate simple tasks.

    Most commands can be run as a regular user. But, as always, depending on what you are doing some commands may need to be run at an elevated prompt. To see all available commands, type “help”. To see help about a specific command use “<command> /?”.

    Navigate & Help

    cd /d H:Change drive to H: drive
    cd \Change directory to C:\
    helpSee all commands.
    <command> /?Get help about command <command>.

    User Information

    net user administrator /active:yesEnable the hidden Administrator acct (run cmd as admin).
    gpupdate /forceUpdate the user’s group policies.
    net user username1 /domainGet current user details (last logon, passwd age, etc).
    gpresult /user <user1> /r | moreGet a list of the user’s domain groups.
    psloggedon \pcname or ipSee who is logged in (sys internals).
    net usersprint a list of all system users.
    sc query | moreDisplay status of active services.
    net localgroup administratorsList all local administrators.
    net localgroup “remote desktop users”List users allowed to login remotely.

    Folder & Files

    dirDisplay files in the current folder.
    cipher s:/<Folder name> Check if a folder/file is encrypted.
    cipher /cDisplay info on the encrypted file.
    mkdirMake a Directory
    find or findstr “Find”Find all lines with the word “joe”.
    del newfile.txtDelete the file newfile.txt.
    move [source] [ target]Move file to new location.
    fc /a monthly.txt sales.txtCompare two text files.
    robocopy /s [src] [dst]Copy directories except empty ones.

    System Information

    msinfo32Launch the system info GUI.
    hostnameDisplay the name of the computer.
    wmic cpu get numberofcores, NumberOfLogicalProcessorsDisplay # of CPU cores and logical processors.
    wmic /node:10.10.56.10 bios get name, versionDisplay BIOS name & ver. from a remote PC.
    wmic os get caption, versionDisplay OS name and version.
    wmic computersystem get manufacturer, modelDisplay PC manufacturer and model.
    systeminfo <hostname> | find “OS Name”Display the OS Name only.
    net shareList all files on the system that you are sharing.

    System Tasks

    msconfigLaunch sys config GUI. Manage startup programs.
    taskkillKill running processes.
    shutdown /rShutdown and reboot the pc.
    mstsc /adminStart an RDP session.
    tasklistdisplay running processes.
    wmic process get description, executablepathdisplay running executables.
    schtasks /query | moreDisplay scheduled tasks

    Networking

    ping -aTest network connectivity and resolve DNS.
    ipconfig /allDisplays current IPv4, DNS server name, and Gateway router IP, and other info.
    nslookupReturns an IP address or a name.
    tracert <url>Trace & displays path to reach an internet host.
    netstat Check the UDP/TCP connections. ( See Article)
    route printList routing table.
    arp -aGet address resolution table.
    netshChange network setting, like whether to use DCHP (See below).
    nbstat Display stats and current connections using NetBIOS over TCP/IP.

    How to Manually Set Your Networking

    Run these commands at an elevated prompt.

    Set a static IP

    Set DHCP from a static IP address

    Set A Primary DNS Server To a static IP

    Set the secondary DNS server to a static IP

    Set your DNS settings to be assigned dynamically

    netsh interface ip set dnsservers name="Local Area Connection" source=dhcp

  • Make a Batch Script to Map Your Drives

    Make a Batch Script to Map Your Drives

    Introduction

    Although Microsoft calls it mapping a drive, in truth, you are just mapping the location of a specific local or remote folder. You are not technically mapping an entire hard drive.

    There are several reasons it is worthwhile to write a batch script that can auto connect your frequently used folders. A common reason is that enterprise users frequently get their network folders disconnected. Problems arise from VPN disconnects, power fluctuations, or other concerns.

    We can make a batch script and save it on their desktop (or in their startup folder) to quickly get their folders re-connected. The user’s just need to double click the script file and it will quickly restore their network folders.

    Map the folders (aka. drives)

    Let’s create a script called ‘mapdrives.bat’ using notepad.

    Add information to the headers. Anything with REM or :: will not be executed.

    Use ‘echo off’, at the top of the script. This tells the script to not display the commands or results to the screen, as they are executed. Use ‘echo.’ to print a blank line, and use just ‘echo’ to print data to the screen.

    Comment your code using descriptors and use ‘net use’ to map the folder paths. Be sure to put quotes around the file path if there is a space somewhere in the path.

    Let’s create a short delay and exit the program. We can add the command ‘pause’ and it will hold the command prompt open until a key is struck or use ‘ping’ and it will wait three seconds and exit automatically.

    Finally, save the file with ‘.bat’ file extension and then double click the file to execute it.

    Open File Explorer and you will see your newly mapped folders.