Loading
Showing posts with label Command Line. Show all posts
Showing posts with label Command Line. Show all posts

Sunday, January 2, 2011

Configuring FTP in Isolation Mode in IIS 6

IIS FTP isolation mode enables you to have a separate directory per FTP user. For example if you had a dozen different users that all need access to your FTP server but you did not want them to see any directories but their own you could setup Isolation Mode. Isolation Mode supports users either on the local computer, or if you are a member of a domain it supports domain users.

We will begin by assuming you have FTP (and IIS) installed. Launch IIS Manager (IIS Manager 6.0 in Windows 2008). NOTE: in Windows 2008 make sure you install the IIS Management Console role so you can manage your FTP sites.
  • Delete or disable the default ftp site
  • Create a new FTP site with desired values - at the FTP User Isolation screen select Isolate Users or Isolate Users using Active Directory (which ever works better for your situation)
  • Specify path for your new FTP site
  • Set FTP Site Access Permissions to both Read and Write
Within the root FTP directory you must create either a directory named localuser or <your_domain_name>, depending on which isolation mode you are using.  In my case I am NOT using Active Directory so I created the directory localuser.

Within the localuser or <your_domain_name> directory create the desired user directories and assign each user sufficient permissions to their respective directory.


Example - creating directories:
md ftproot
md ftproot\localuser
md ftproot\localuser\localuser1
md ftproot\localuser\localuser2
md ftproot\localuser\localuser3
Example - setting Create NTFS permissions on each respective directory:
cacls ftproot\localuser\localuser1 /E /G localuser1:C
cacls ftproot\localuser\localuser2 /E /G localuser2:C
cacls ftproot\localuser\localuser3 /E /G localuser3:C

Wednesday, July 28, 2010

Get Yesterday's date in MS DOS Batch file

A while back while I was trying to figure out the best way to gather some log files from Amazon S3 buckets and some web servers I run.  These resources are currently generating around 10-15GB of uncompressed log files daily.  Besides being fairly large in size the S3 (and CloudFront) log files are numerous.  Any given bucket can easily generate 1,000 or more log files per day - that's a whole other story. . .

Anyway, I wanted to be able to run a process sometime after midnight that would gather and zip the previous day's files and stash the zipped files in another location for archival.  It's pretty easy to calculate the previous day's date if it's in the middle of the month, but what if it's the first of the month, first of the year, and what about leap year, etc., etc. . . ?  So I searched around the web a bit and came across a great solution to this issue on Experts Exchange (Get Yesterday date in MS DOS Batch file).  Thanks to SteveGTR for this one.

I have modified the original script a bit to suite my needs.  Most notably at the end of the script I create two variables, IISDT and AWSDT, to match IIS and Amazon Web Services (S3 and CloudFront) log formats, respectively.  I use this in a simple batch file which is executed like, "gather_log_files.bat 1."  The number "1" is passed into the script which calculates the date of "1" day before the current date.  Of course you could pass any number in there to generate a date x days in the past.  It's very slick. NOTE: If you don't specify a number after the batch file "1" is assumed.

So, without further ado, here's the script.
@echo off

set yyyy=

set $tok=1-3
for /f "tokens=1 delims=.:/-, " %%u in ('date /t') do set $d1=%%u
if "%$d1:~0,1%" GTR "9" set $tok=2-4
for /f "tokens=%$tok% delims=.:/-, " %%u in ('date /t') do (
for /f "skip=1 tokens=2-4 delims=/-,()." %%x in ('echo.^|date') do (
set %%x=%%u
set %%y=%%v
set %%z=%%w
set $d1=
set $tok=))

if "%yyyy%"=="" set yyyy=%yy%
if /I %yyyy% LSS 100 set /A yyyy=2000 + 1%yyyy% - 100

set CurDate=%mm%/%dd%/%yyyy%
set dayCnt=%1

if "%dayCnt%"=="" set dayCnt=1

REM Substract your days here
set /A dd=1%dd% - 100 - %dayCnt%
set /A mm=1%mm% - 100

:CHKDAY
if /I %dd% GTR 0 goto DONE
set /A mm=%mm% - 1
if /I %mm% GTR 0 goto ADJUSTDAY
set /A mm=12
set /A yyyy=%yyyy% - 1

:ADJUSTDAY
if %mm%==1 goto SET31
if %mm%==2 goto LEAPCHK
if %mm%==3 goto SET31
if %mm%==4 goto SET30
if %mm%==5 goto SET31
if %mm%==6 goto SET30
if %mm%==7 goto SET31
if %mm%==8 goto SET31
if %mm%==9 goto SET30
if %mm%==10 goto SET31
if %mm%==11 goto SET30
REM ** Month 12 falls through

:SET31
set /A dd=31 + %dd%
goto CHKDAY

:SET30
set /A dd=30 + %dd%
goto CHKDAY

:LEAPCHK
set /A tt=%yyyy% %% 4
if not %tt%==0 goto SET28
set /A tt=%yyyy% %% 100
if not %tt%==0 goto SET29
set /A tt=%yyyy% %% 400
if %tt%==0 goto SET29

:SET28
set /A dd=28 + %dd%
goto CHKDAY

:SET29
set /A dd=29 + %dd%
goto CHKDAY

:DONE
if /I %mm% LSS 10 set mm=0%mm%
if /I %dd% LSS 10 set dd=0%dd%

REM Set IIS and AWS date variables
set IISDT=%yyyy:~2,2%%mm%%dd%
set AWSDT=%yyyy%-%mm%-%dd%
The results would look like:
IIS Date: 20100727
AWS Date: 2010-07-27

Friday, January 8, 2010

How To Use Wget - Includes Several Examples Using Wget

wget is a great command line utility that is natively available in Linux and can be downloaded for Windows (see also GNU WGet for Windows (Windows 7, Vista, XP, etc.)). wget can be used for many download situations including large files, recursive downloads, non-interactive downloads, multiple file downloads, etc.

Note: options ARE case sensitive.

1. Download a single file with wget using no options.
wget http://ftp.gnu.org/gnu/wget/wget-latest.tar.gz
While downloading, wget will display a progress bar with the following information:
  • % of download completion
  • Download progress in bytes
  • Current download speed
  • Estimated time remaining
Download in progress









Completed download










2. Download a file saving with a different name using wget -O
wget http://www.vim.org/scripts/download_script.php?src_id=7701
Even though the downloaded file is in zip format, it will be saved with the name download_script.php?src_id=7701 without the -O switch.

To modify this behavior specify the output file name using the -O option.
wget -O taglist.zip http://www.vim.org/scripts/download_script.php?src_id=7701
3. Specify download speed / download rate Using wget –limit-rate

While executing the wget, by default it will try to use all possible bandwidth. You can limit the download speed using the –limit-rate switch.
wget --limit-rate=200k http://ftp.gnu.org/gnu/wget/wget-latest.tar.gz
4. Restart a download which stopped in the middle using wget -c.
wget -c http://ftp.gnu.org/gnu/wget/wget-latest.tar.gz
5. Download in the background with wget -b
wget -b http://ftp.gnu.org/gnu/wget/wget-latest.tar.gz





The download will begin and give back the shell prompt to you. You can always check the status of the download using tail -f  (Linux only) .
tail -f wget-log
6. Mask user agent and display wget like browser using wget –user-agent

Some websites can disallow you to download its page by identifying that the user agent is not a browser. So you can mask the user agent by using –user-agent options and show wget like a browser.
wget --user-agent="Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.3) Gecko/2008092416 Firefox/3.0.3" http://ftp.gnu.org/gnu/wget/wget-latest.tar.gz
7. Test URL using wget –spider.  This will test that the file exists, but not perform the download.
wget --spider http://ftp.gnu.org/gnu/wget/wget-latest.tar.gz








8. Increase total number of retry attempts using wget –tries.
wget --tries=75 http://ftp.gnu.org/gnu/wget/wget-latest.tar.gz
9. Download multiple files / URLs using wget -i

First, store all the download files or URLs in a text file:
URL1
URL2
URL3
URL4

Next, give the download-file-list.txt as argument to wget using -i option.
wget -i download-file-list.txt
10. Download a full website using wget –mirror
wget --mirror -p --convert-links -P ./LOCAL-DIR WEBSITE-URL
  • –mirror: enable mirroring
  • -p: download all files that are necessary to properly display a given HTML page
  • –convert-link: after the download, convert the links in document for local viewing
  • -P ./LOCAL-DIR: save all the files and directories to the specified directory
11. Skip certain file types while downloading using wget –reject.  In order to download all content except .gif images use the following.
wget --reject=gif WEBSITE-TO-BE-DOWNLOADED
12. Log messages to a log file instead of stderr using wget -o.  To redirect output to a log file instead of the terminal.
wget -o download.log DOWNLOAD-URL
13. Quit downloading when certain size is exceeded using wget -Q.
wget -Q5m -i FILE-WHICH-HAS-URLS
14. Download only certain file types using wget -r -A

You can use this for the following situations
  • Download all images from a website
  • Download all videos from a website
  • Download all PDF files from a website
wget -r -A.pdf http://url-to-webpage-with-pdfs/
15. You can use wget to perform FTP downloads.
wget ftp-url
FTP download using wget with username and password authentication.
wget --ftp-user=USERNAME --ftp-password=PASSWORD DOWNLOAD-URL
Note: username and password can be used for HTTP and HTTPS downloads as well using --http-user=USER, --http-password=PASS respectively.

More

Wednesday, December 9, 2009

Install Windows Server 2008 Features with servermanagercmd.exe at the Command Prompt

Although Microsoft continues to expand PowerShell with more capability, the command prompt has not been left behind in Windows Server 2008. In fact, with this latest Windows Server release, the command prompt gains some capability, including a tool that allows administrators to add or remove features on a Windows Server 2008 installation with servermanagercmd.exe, which replicates some of the functionality from the Windows Server 2008 Server Manager. Through the use of various command line options, you can quickly and easily add or remove features and roles to or from your server.

The command requires a parameter indicating the action that you wish to perform and, for some parameters, additional information such as which features you want to manage. The list below outlines some of the parameters available with servermanagercmd.
  • -query: Output a list of the roles and features currently installed on your server. This command also shows you the roles and features that are available, but not yet installed.
  • -install: Installs the roles or features that you specify on the command line. Add -allSubFeatures to the command line when using -install in order to add the supporting roles/features to a specified parent role/feature. As you are well aware some components require a server reboot in order to complete. To automate a server restart that takes place after the installation of a role/feature requiring a restart, use -restart.
  • -remove: This is the opposite of the install command and removes the specified roles or features.


The table below provides you with a complete list of the components installable using the servermanagercmd command. The first column is the overall feature name. For some features, roles, or services, there are multiple components available. The second column of the table gives you a complete list of all subcomponents while the third column is the identifier to use with the -install or -remove parameter.

Role / Service or Main Feature
R/S/F Name
Installatiom command
DHCP Server
DHCP Server
DHCP
Print Services
Print Server
Print-Services
Internet Printing
Print-Internet
LPD Service
Print-LPD-Service
Terminal Services
Terminal Services
Terminal-Services
Terminal Server
TS-Terminal-Server
TS Licensing
TS-Licensing
TS Gateway
TS-Gateway
TS Web Access
TS-Web-Access
TS Session Broker
TS-Session-Broker
Active Directory Domain Services
AD
N/A
Active Directory Domain Controller
ADDS-Domain-Controller
Identity Management for UNIX
ADDS-Identity-Management
Server for Network Information Service
ADDS-NIS
Password Synchronization
ADDS-Password-Sync
DNS Server
DNS
File Services
File Services
N/A
Distributed File System (DFS)
FS-DFS
DFS Namespace
FS-DFS-Namespace
DFS Replication
FS-DFS-Replication
File Server Resource Manager
FS-Resource-Manager
Services for Network File System
FS-NFS-Services
Windows Search Service
FS-Search-Service
Windows Server 2003 File Services
FS-Win2003-Services
File Replication Service
FS-Replication
Indexing Service
FS-Indexing-Service
Web Server
Web Server (IIS)
Web-Server
Internet Information Services
Web-WebServer
Common HTTP Features
Web-Common-Http
Static Content
Web-Static-Content
Default Document
Web-Default-Doc
Directory Browsing
Web-Dir-Browsing
HTTP Errors
Web-Http-Errors
HTTP Redirection
Web-Http-Redirect
Application Development
Web-App-Development
ASP.NET
Web-Asp-Net
.NET Extensibility
Web-Net-Ext
ASP
Web-ASP
CGI
Web-CGI
ISAPI Extensions
Web-ISAPI-Ext
ISAPI Filters
Web-ISAPI-Filter
Server Side Includes
Web-Includes
Health and Diagnostics
Web-Health
HTTP Logging
Web-Http-Logging
Logging Tools
Web-Log-Libraries
Request Monitor
Web-Request-Monitor
Tracing
Web-Http-Tracing
Custom Logging
Web-Custom-Logging
ODBC Logging
Web-ODBC-Logging
Security
Web-Security
Basic Authentication
Web-Basic-Auth
Windows Authentication
Web-Windows-Auth
Digest Authentication
Web-Digest-Auth
Client Certificate Mapping Authentication
Web-Client-Auth
IIS Client Certificate Mapping Authentication
Web-Cert-Auth
URL Authorization
Web-Url-Auth
Request Filtering
Web-Filtering
IP and Domain Restrictions
Web-IP-Security
Performance
Web-Performance
Static Content Compression
Web-Stat-Compression
Dynamic Content Compression
Web-Dyn-Compression
Management Tools
Web-Mgmt-Tools
IIS Management Console
Web-Mgmt-Console
IIS Management Scripts and Tools
Web-Scripting-Tools
Management Service
Web-Mgmt-Service
IIS 6 Management Compatibility
Web-Mgmt-Compat
IIS 6 Metabase Compatibility
Web-Metabase
IIS 6 WMI Compatibility
Web-WMI
IIS 6 Scripting Tools
Web-Lgcy-Scripting
IIS 6 Management Console
Web-Lgcy-Mgmt-Console
FTP Publishing Service
Web-Ftp-Publishing
FTP Server
Web-Ftp-Server
FTP Management Console
Web-Ftp-Mgmt-Console
Active Directory Federation Services
ADFS
None
Federation Service
ADFS-Federation
Federation Service Proxy
ADFS-Proxy
Web Agents
ADFS-Web-Agents
Claims-aware Agent
ADFS-Claims
Windows Token-based Agent
ADFS-Windows-Token
Active Directory Lightweight Directory Services
Formerly ADAM
ADLDS
Application Server
Application Server
Application-Server
Application Server Core
AS-AppServer-Core
Web Server Support
AS-Web-Support
COM+ Network Access
AS-Ent-Services
TCP Port Sharing
AS-TCP-Port-Sharing
Windows Process Activation Service Support
AS-WAS-Support
HTTP Activation
AS-HTTP-Activation
Message Queuing Activation
AS-MSMQ-Activation
TCP Activation
AS-TCP-Activation
Named Pipes Activation
AS-Named-Pipes
Distributed Transaction Support
AS-Dist-Transaction
Incoming Remote Transactions
AS-Incoming-Trans
Outgoing Remote Transactions
AS-Outgoing-Trans
WS-Atomic Transaction Support
AS-WS-Atomic
Active Directory Certificate Services
Active Directory Certificate Services
N/A
Certification Authority
ADCS-Cert-Authority or AD-Certificate
Online Certificate Status Protocol
ADCS-Online-Cert
Fax Server
Fax Server
Fax
Network Policy and Access Services
Network Policy and Access Services
NPAS
Network Policy Server
NPAS-Policy-Server
NPAS Routing and Remote Access Services
NPAS-RRAS-Services
Remote Access Service
NPAS-RRAS
Routing
NPAS-Routing
Health Registration Authority
NPAS-Health
Windows Deployment Services
Windows Deployment Services
WDS
Hyper-V
Hyper-V
Hyper-V
Failover Clustering
Failover Clustering
Failover-Clustering
Network Load Balancing
Network Load Balancing
NLB
Desktop Experience
Desktop Experience
Desktop-Experience
.NET Framework 3.0 Features
.NET Framework 3.0 Features
NET-Framework
.NET Framework 3.0
.NET Framework 3.0
NET-Framework-Core
XPS Viewer
XPS Viewer
NET-XPS-Viewer
Windows Communication Foundation Activation Components
Windows Communication Foundation Activation Components
NET-Win-CFAC
HTTP Activation
HTTP Activation
NET-HTTP-Activation
Non-HTTP Activation
Non-HTTP Activation
NET-Non-HTTP-Activ
Windows System Resource Manager
Windows System Resource Manager
WSRM
Wireless Networking
Wireless Networking
Wireless-Networking
Windows Server Backup
Windows Server Backup
Backup
WINS Server
WINS Server
WINS-Server
Remote Assistance
Remote Assistance
Remote-Assistance
Simple TCP/IP Services
Simple TCP/IP Services
Simple-TCPIP
Telnet Client
Telnet Client
Telnet-Client
Telnet Server
Telnet Server
Telnet-Server
Subsystem for UNIX-based Applications
Subsystem for UNIX-based Applications
Subsystem-UNIX-Apps
RPC over HTTP Proxy
RPC over HTTP Proxy
RPC-over-HTTP-Proxy
SMTP Server
SMTP Server
SMTP-Server
LPR Port Monitor
LPR Port Monitor
LPR-Port-Monitor
Storage Manager for SANs
Storage Manager for SANs
Storage-Mgr-SANS
BITS Server Extensions
BITS Server Extensions
BITS
Message Queuing
Message Queuing
MSMQ
Message Queuing Services
MSMQ-Services
Message Queuing Server
MSMQ-Server
Directory Service Integration
MSMQ-Directory
Message Queuing Triggers
MSMQ-Triggers
HTTP Support
MSMQ-HTTP-Support
Multicasting Support
MSMQ-Multicasting
Routing Service
MSMQ-Routing
Windows 2000 Client Support
MSMQ-Win2000
Messaging Queue DCOM Proxy
MSMQ-DCOM
Windows Process Activation Service
Windows Process Activation Service
WAS
Process Model
WAS-Process-Model
.NET Environment
WAS-NET-Environment
Configuration APIs
WAS-Config-APIs
Windows Internal Database
Windows Internal Database
Windows-Internal-DB
BitLocker Drive Encryption
BitLocker Drive Encryption
BitLocker
Multipath I/O
Multipath I/O
Multipath-IO
Internet Storage Naming Server
Internet Storage Naming Server
ISNS
Removable Storage Manager
Removable Storage Manager
Removable-Storage
TFTP Client
TFTP Client
TFTP-Client
SNMP Services
SNMP Services
SNMP-Services
SNMP Service
SNMP-Service
SNMP WMI Provider
SNMP-WMI-Provider
Services for Network File System
Services for Network File System
NFS-Services
Internet Printing Client
Internet Printing Client
Internet-Print-Client
Peer Name Resolution Protocol
Peer Name Resolution Protocol
PNRP
Connection Manager Administration Kit
Connection Manager Administration Kit
CMAK
Remote Server Administration Tools
Remote Server Administration Tools
RSAT
Role administration tools
RSAT-Role-Tools
Active Directory Certificate Services Tools
RSAT-ADCS
Active Directory Domain Services Tools
RSAT-ADDS
Active Directory Domain Controller Tools
RSAT-ADDC
Server for NIS Tools
RSAT-SNIS
Active Directory Lightweight Directory Services Tools
RSAT-ADLDS
Active Directory Rights Management Services (AD RMS) Tools
RSAT-RMS
DHCP Server Tools
RSAT-DHCP
DNS Server Tools
RSAT-DNS
Fax Server Tools
RSAT-Fax
DFS Management Console Tools
RSAT-DFS-Mgnt-Con
File Server Resource Manager Management Console Tools
RSAT-FSRM-Mgnt
Hyper-V Tools
RSAT-Hyper-V
Services for Network File System Tools
RSAT-NFS-Admin
File Services Tools
RSAT-File-Services
Network Policy and Access Services Tools
RSAT-NPAS
Health Registration Authority Tools
RSAT-HRA
Network Policy Server Tools
RSAT-NPS
Print Services Tools
RSAT-Print-Services
Web Server (IIS) Tools
RSAT-Web-Server
Terminal Services Tools
RSAT-TS
TS RemoteApp Tools
RSAT-TS-RemoteApp
TS Gateway Tools
RSAT-TS-Gateway
TS Licensing Tools
RSAT-TS-Licensing
UDDI Services Tools
RSAT-UDDI
Feature administration tools
RSAT-Feature-Tools
BitLocker Drive Encryption Tools
RSAT-BitLocker
BITS Server Extensions Tools
RSAT-BITS-Server
Failover Clustering Tools
RSAT-Clustering
Network Load Balancing Tools
RSAT-NLB
SMTP Server Tools
RSAT-SMTP
Windows Deployment Services Tools
RSAT-WDS
WINS Server Tools
RSAT-WINS
Hyper-V Tools
RSAT-Hyper-V
Windows PowerShell
Windows PowerShell
PowerShell
Group Policy Management
Group Policy Management
GPMC
Quality Windows Audio Video Experience
Quality Windows Audio Video Experience
Qwave

Examples
  • Using servermanagercmd to activate terminal services
You can selectively enable terminal server services with:
servermanagercmd -install TS-TerminalServer
Terminal Services options
[ ] Terminal Services  [Terminal-Services]
    [ ] Terminal Server  [TS-Terminal-Server]
    [ ] TS Licensing  [TS-Licensing]
    [ ] TS Session Broker  [TS-Session-Broker]
    [ ] TS Gateway  [TS-Gateway]
    [ ] TS Web Access  [TS-Web-Access]

How to: Reverse DNS from Windows Command Line using Ping

Here's a quick and easy way to do a Reverse DNS (RDNS) lookup using ping.exe from a Windows command prompt using the -a switch.
ping -a <IP Address>
Example
ping -a 76.96.54.12
This example will resolve the address as follows:
Pinging www4.comcast.net [76.96.54.12] with 32 bytes of data:

Reply from 76.96.54.12: bytes=32 time=66ms TTL=51
Reply from 76.96.54.12: bytes=32 time=7ms TTL=51
Reply from 76.96.54.12: bytes=32 time=7ms TTL=51
Reply from 76.96.54.12: bytes=32 time=7ms TTL=51

Ping statistics for 76.96.54.12:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 7ms, Maximum = 66ms, Average = 21ms

Wednesday, December 2, 2009

How to: Change / Setup bash custom prompt (PS1)

So how do you setup, change and pimp out Linux / UNIX shell prompt?

Most of us work with a shell prompt. By default most Linux distro displays hostname and current working directory. You can easily customize your prompt to display information important to you. You change look and feel by adding colors. In this small howto I will explain howto setup:
  • Customize a bash shell to get a good looking prompt
  • Configure the appearance of the terminal
  • Apply themes using bashish
  • Howto pimp out your shell prompt
Prompt is controled via a special shell variable. You need to set PS1, PS2, PS3 and PS4 variables. If set, the value is executed as a command prior to issuing each primary prompt.
  • PS1 - The value of this parameter is expanded (see PROMPTING below) and used as the primary prompt string. The default value is \s-\v\$ .
  • PS2 - The value of this parameter is expanded as with PS1 and used as the secondary prompt string. The default is >
  • PS3 - The value of this parameter is used as the prompt for the select command
  • PS4 - The value of this parameter is expanded as with PS1 and the value is printed before each command bash displays during an execution trace. The first character of PS4 is replicated multiple times, as necessary, to indicate multiple levels of indirection. The default is +

How do I display current prompt setting?

Simply use echo command, enter:
$ echo $PS1
Output:
\\u@\h \\W]\\$

How do I modify or change the prompt?

Modifying the prompt is easy task. Just assign a new value to PS1 and hit enter key:
My old prompt --> [admin@105r2 ~]$
PS1="MyNewPrompt : "
Output: My new prompt
MyNewPrompt : 
So when executing interactively, bash displays the primary prompt PS1 when it is ready to read a command, and the secondary prompt PS2 when it needs more input to complete a command. Bash allows these prompt strings to be customized by inserting a number of backslash-escaped special characters that are decoded as follows:
  • \a : an ASCII bell character (07)
  • \d : the date in "Weekday Month Date" format (e.g., "Tue May 26")
  • \D{format} : the format is passed to strftime(3) and the result is inserted into the prompt string; an empty format results in a locale-specific time representation. The braces are required
  • \e : an ASCII escape character (033)
  • \h : the hostname up to the first '.'
  • \H : the hostname
  • \j : the number of jobs currently managed by the shell
  • \l : the basename of the shell’s terminal device name
  • \n : newline
  • \r : carriage return
  • \s : the name of the shell, the basename of $0 (the portion following the final slash)
  • \t : the current time in 24-hour HH:MM:SS format
  • \T : the current time in 12-hour HH:MM:SS format
  • \@ : the current time in 12-hour am/pm format
  • \A : the current time in 24-hour HH:MM format
  • \u : the username of the current user
  • \v : the version of bash (e.g., 2.00)
  • \V : the release of bash, version + patch level (e.g., 2.00.0)
  • \w : the current working directory, with $HOME abbreviated with a tilde
  • \W : the basename of the current working directory, with $HOME abbreviated with a tilde
  • \! : the history number of this command
  • \# : the command number of this command
  • \$ : if the effective UID is 0, a #, otherwise a $
  • \nnn : the character corresponding to the octal number nnn
  • \\ : a backslash
  • \[ : begin a sequence of non-printing characters, which could be used to embed a terminal control sequence into the prompt
  • \] : end a sequence of non-printing characters
Let us try to set the prompt so that it can display today’d date and hostname:
PS1="\d \h $ "
Output:
Wed Dec 02 ServerName $ 
Now setup prompt to display date/time, hostname and current directory:
$ PS1="[\d \t \u@\h:\w ] $ "
Output:
[Wed Dec 02 18:54:07 admin@ServerName:~ ] $

How do I add colors to my prompt?

You can change the color of your shell prompt to impress your friend or to make your own life quite easy while working at command prompt.

Putting it all together

Let us say when you login as root/superuser, you want to get visual confirmation using red color prompt. To distinguish between superuser and normal user you use last character in the prompt, if it changes from $ to #, you have superuser privileges. So let us set your prompt color to RED when you login as root, otherwise display normal prompt.

Open /etc/bashrc (Redhat and friends) / or /etc/bash.bashrc (Debian/Ubuntu) or /etc/bash.bashrc.local (Suse and others) file and append following code:
# vi /etc/bashrc
or
$ sudo gedit /etc/bashrc
Append the code as follows
# If id command returns zero, you’ve root access.
if [ $(id -u) -eq 0 ];
then # you are root, set red colour prompt
  PS1="\\[$(tput setaf 1)\\]\\u@\\h:\\w #\\[$(tput sgr0)\\]"
else # normal
  PS1="[\\u@\\h:\\w] $"
fi

Close and save the file.

You can also create complex themes for your bash shell using bashish. Bashish is a theme enviroment for text terminals. It can change colors, font, transparency and background image on a per-application basis. Additionally Bashish supports prompt changing on common shells such as bash, zsh and tcsh. Install bashish using rpm or apt-get command:
# rpm -ivh bashish*
OR
# dpkg -i bashish*
Now start bashish for installing user configuration files:
$ bashish
Next you must restart your shell by typing the following command:
$ exec bash
To configure the Bashish theme engine, run
$ bashishtheme
basish in action (screenshots from official site):
flower.png
urbandawn - based on an artwork by grevenlx
Finally, you can always use aterm or other terminal program such as rxvt. It supports nice visual effect , like transparency, tinting and much more by visiting profile menu. Select your terminal > click on Edit menu bar > Profiles > Select Profile > Click on Edit button > Select Effects tab > Select transparent background > Close.

BASH Shell change the color of the shell prompt in Linux or UNIX


You can change the color of your shell prompt to impress your friend or to make your own life quite easy while working at command prompt.
In the Linux default shell is BASH.
Your current prompt setting is stored in PS1 shell variable. There are other variables too, like PS2, PS3 and PS4.
Bash displays the primary prompt PS1 when it is ready to read a command, and the secondary prompt PS2 when it needs more input to complete a command. Bash allows these prompt strings to be customized by inserting a number of backslash-escaped special characters.

Display current BASH prompt (PS1)

Use echo command to display current BASH prompt:
$ echo $PS1Output:
\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\u@\h:\w\$
By default the command prompt is set to: [\u@\h \W]\$. Backslash-escaped special characters are decoded as follows:
  • \u: Display the current username
  • \h: Display the hostname
  • \W: Print the current working directory

Task: Modify current BASH prompt

Use export command to setup a new shell prompt:$ export PS1="[\\u@\\H \\W \\@]\\$"
Where,
  • \H: Display FQDN hostname
  • \@: Display current time in 12-hour am/pm format

Add colors to the prompt

To add colors to the shell prompt use the following export command syntax:
'\e[x;ym $PS1 \e[m'
Where,
  • \e[ Start color scheme
  • x;y Color pair to use (x;y)
  • $PS1 is your shell prompt
  • \e[m Stop color scheme
To the prompt to blue, type the command:
$ export PS1="\e[0;34m[\u@\h \W]\$ \e[m "

Color codes

Color
Code
Black
0;30
Blue
0;34
Green
0;32
Cyan
0;36
Red
0;31
Purple
0;35
Brown
0;33
Blue
0;34
Green
0;32
Cyan
0;36
Red
0;31
Purple
0;35
Brown
0;33
Replace digit 0 with 1 to get light color version.

How to make the prompt setting permanent

Your new shell prompt setting is temporary i.e. when you logout setting will be lost. To have it set everytime you login to your workstation add above export command to your .bash_profile file or .bashrc file.
$ cd
$ vi .bash_profile
OR
$ vi .bashrc
Append export line:
export PS1="\e[0;31m[\u@\h \W]\$ \e[m"
Save and close the file.

tput command

You can also use tput command. For example display RED prompt use tput as follows:
export PS1="\[$(tput setaf 1)\]\u@\h:\w $ \[$(tput sgr0)\]"

handy tput commands

  • tput bold - Bold effect
  • tput rev - Display inverse colors
  • tput sgr0 - Reset everything
  • tput setaf {CODE}- Set foreground color, see color {CODE} below
  • tput setab {CODE}- Set background color, see color {CODE} below

Colors {code} code for tput command

Color {code}
Color
0
Black
1
Red
2
Green
3
Yellow
4
Blue
5
Magenta
6
Cyan
7
White
Read the man page of bash and tput command for more information.

Sunday, November 29, 2009

How to kill and logout a user in Linux

You can check who is logged in to a Linux system by executing
who or w commands
and then you can get the user PID
ps aux | grep username or tty
and kill it
kill -KILL PID
or you can use pkill command and kill the user by its username
pkill -KILL -u username
It would be nice to send the users a warning message before logging them out.

Disable/Enable User Access Control (UAC) on Windows 7 or Vista from the Command Line

Microsoft introduced User Account Control (UAC) in Windows Vista. UAC enables users to perform common tasks as non-administrators, called standard users in Windows (Vista and Windows 7), and as administrators without having to switch users, log off, or use Run As. A standard user account is synonymous with a user account in Windows XP. User accounts that are members of the local Administrators group will run most applications as a standard user. By separating user and administrator functions while enabling productivity, UAC is an important enhancement for Windows.

Disable UAC from the command line
%systemroot%\System32\cmd.exe /k %windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f
Enable UAC from the command line
%systemroot%\System32\cmd.exe /k %windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 1 /f
A couple caveats
  1. Must be run with administrative rights.  You could right-click on Command Prompt shortcut and select Run as Administrator.
  2. You may have to reboot for changes to take affect.
You can also enable or disable UAC from the Control Panel.